简体   繁体   English

使用Python自动裁剪图像

[英]Automatically cropping an image using Python

I want to automatically crop an image using OpenCV into many images, the number of output images is variable. 我想使用OpenCV自动将图像裁剪成许多图像,输出图像的数量是可变的。 I started by replacing the white background by a transparent background. 我首先用透明背景替换了白色背景。

The input image: 输入图像: 在此处输入图片说明

I replace the white background by a transparent background using this script: 我使用以下脚本将白色背景替换为透明背景:

from PIL import Image

img = Image.open('./images/SPORTS/546.png')
img = img.convert("RGBA")
datas = img.getdata()

newData = []
for item in datas:
    if item[0] == 253 and item[1] == 252 and item[2] == 252:
        newData.append((255, 255, 255, 0))
    else:
        newData.append(item)

img.putdata(newData)
img.show()
img.save("split_image_example.png", "PNG")

So in this example I want to get 4 separated images. 因此,在此示例中,我想获得4张分离的图像。

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

You can use BoundingRect() on findContour() See http://docs.opencv.org/2.4/doc/tutorials/imgproc/shapedescriptors/bounding_rects_circles/bounding_rects_circles.html 您可以在findContour()上使用BoundingRect(),请参见http://docs.opencv.org/2.4/doc/tutorials/imgproc/shapedescriptors/bounding_rects_circles/bounding_rects_circles.html

For your case : 对于您的情况:

img=cv2.imread(path_to_your_image,0)
if img is None:
    sys.exit("No input image") #good practice

#thresholding your image to keep all but the background (I took a version of your
#image with a white background, you may have to adapt the threshold
thresh=cv2.threshold(img, 250, 255, cv2.THRESH_BINARY_INV);
res=thresh[1]

#dilating the result to connect all small components in your image
kernel=cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
for i in range(10):
    res=cv2.dilate(res,kernel)

#Finding the contours
 img2,contours,hierarchy=
cv2.findContours(res,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)


cpt=0
for contour in contours:
    #finding the bounding rectangle of your contours
    rect=cv2.boundingRect(contour)
    #cropping the image to the value of the bounding rectangle
    img2=img[rect[1]:rect[1]+rect[3],rect[0]:rect[0]+rect[2]]
    cv2.imwrite("path_you_want_to_save"+str(cpt)+".png", img2)
    cpt=cpt+1;

This is a quick code, you may want to change : the saving method, the contour computing parameters, the dilatation method.... Most importantly, it suits the image you've given here but may not be appropriate for cases where your objects are closer by, or are more "sparse" (if dilating can't merge them together) 这是一个快速的代码,您可能需要更改:保存方法,轮廓计算参数,膨胀方法...。最重要的是,它适合您在此处给出的图像,但可能不适用于您的对象的情况更近或更“稀疏”(如果扩展无法将它们合并在一起)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM