2017-01-19 8 views
0

OpenCVを使用して画像を自動的にトリミングしたい場合、出力画像の数は可変です。白い背景を透明な背景に置き換えることから始めました。Pythonを使用して自動的に画像を切り出す

入力画像: enter image description here

私はこのスクリプトを使用して、透明な背景で白の背景を置き換える:

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枚の分割画像を取得したいです。

enter image description hereenter image description hereenter image description hereenter image description here

答えて

2

あなたは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; 

このクイックコードで、あなたがしたいこと変更:保存方法、輪郭計算パラメータ、拡張方法... ほとんどのインポートあなたがここに与えたイメージに合っていますが、あなたのオブジェクトが近くにある場合や、より疎な場合(もしそれらが一緒にマージできない場合)

+0

ありがとうございますエラーメッセージ:img2、contours、hierarchy = cv2.findContours(res、cv2.RETR_EXTERNAL、cv2.CHAIN_APPROX_SIMPLE) ValueError:解凍するために2つ以上の値が必要です。 –

+0

img2、contours = cv2.findContours(res 、cv2.RETR_EXTERN AL、cv2.CHAIN_APPROX_ SIMPLE) – Soltius

+0

しきい値パラメータはどのようにして選択できますか? 'cv2.threshold(img、250、255、cv2.THRESH_BINARY_INV); –

関連する問題