如何从JPEG裁剪多个矩形或正方形? [英] How to crop multiple rectangles or squares from JPEG?

查看:123
本文介绍了如何从JPEG裁剪多个矩形或正方形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jpeg,我想在其中裁剪包含图形的部分(底部的那部分)。

I have a jpeg from where I want to crop a portion containing graph (the one in the bottom portion).

到目前为止,我使用此代码来实现相同:

As of now I used this code to achieve the same:

from PIL import Image

img = Image.open(r'D:\aakash\graph2.jpg')
area = (20, 320, 1040, 590)
img2 = img.crop(area)
# img.show()
img2.show()

但是我通过多次猜测x1,y1,x2,y2来实现这一点

But I achieved this by guessing the x1, y1, x2, y2 multiple times to arrive at this (guess work).

裁剪前的图像:

Image before cropping:

裁剪后的图像:

Image after cropping:

我完全是新手基于某些逻辑的图像裁剪。如果位置相同,如何成功裁剪所有图形以创建单独的图像?

I'm totally novice in image cropping based on some logic. How can I successfully crop all graphs to create separate images given the positions are same?

更新:我相信,这不可能重复之所以要解决这个问题,是因为尽管逻辑上是相同的,但是集群逻辑的工作方式却有所不同。在这个问题中,只有2条垂直白线可以划分,但是这里有2条水平线和2条垂直线,我几乎不知道如何使用KMeans解决此类图像聚类。

Update: I believe, it is not a possible duplicate of that problem because, even though logically that's same, but the way the clustering logic will work is different. In that question, there are only 2 vertical white lines to divide, but here, there's two horizontal and two vertical lines, and I hardly have a clue on how to use KMeans to solve this kind of image clustering.

sklearn's KMeans 方面的专家的帮助下解决此类问题将受到高度赞赏。

Help from someone who's an expert with sklearn's KMeans to solve this kind of problem shall be highly appreciated.

推荐答案

这是另一种方法,但是使用PIL / Pillow和 skimage 而不是OpenCV:

Here's another way to do it, but using PIL/Pillow and skimage rather than OpenCV:

#!/usr/local/bin/python3

import numpy as np
from PIL import Image, ImageFilter
from skimage.measure import label, regionprops

# Load image and make Numpy version and greyscale PIL version
pim = Image.open('article.jpg')
n   = np.array(pim)
pgr = pim.convert('L')

# Threshold to make black and white
thr = pgr.point(lambda p: p < 230 and 255)
# Following line is just for debug
thr.save('result-1.png')

# Median filter to remove noise
fil = thr.filter(ImageFilter.MedianFilter(11))
# Following line is just for debug
fil.save('result-2.png')

# Make Numpy version for skimage to use
nim = np.array(fil)

# Image is now white blobs on black background, so label() it
label_image=label(nim)

# Iterate through blobs, saving each to disk
i=0
for region in regionprops(label_image):
   if region.area >= 100:
      # Extract rectangle containing blob and save
      name="blob-" + str(i) + ".png"
      minr, minc, maxr, maxc = region.bbox
      Image.fromarray(n[minr:maxr,minc:maxc,:]).save(name)
      i = i + 1

给出以下输出图像:

中间的调试映像为 result-1.png

结果2。 png

这篇关于如何从JPEG裁剪多个矩形或正方形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆