[英]Automatically cropping an image using Python
我想使用OpenCV
自動將圖像裁剪成許多圖像,輸出圖像的數量是可變的。 我首先用透明背景替換了白色背景。
我使用以下腳本將白色背景替換為透明背景:
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")
因此,在此示例中,我想獲得4張分離的圖像。
您可以在findContour()上使用BoundingRect(),請參見http://docs.opencv.org/2.4/doc/tutorials/imgproc/shapedescriptors/bounding_rects_circles/bounding_rects_circles.html
對於您的情況:
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;
這是一個快速的代碼,您可能需要更改:保存方法,輪廓計算參數,膨脹方法...。最重要的是,它適合您在此處給出的圖像,但可能不適用於您的對象的情況更近或更“稀疏”(如果擴展無法將它們合並在一起)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.