2017-10-22 15 views
0

opencvを使用してイメージ内の最大の輪郭/オブジェクトを識別するコードスニペットで作業しようとしています。下のコードはバウンディングボックスを作成しますが、バウンディングボックスを別の画像として保存する最良の方法は何ですか。画像内で最大のオブジェクトを新しいjpgファイルとして保存できます。ここで私が働いているコードは次のとおりです。バウンディングボックスの内容を新しい画像として保存する - opencv python

import numpy as np 
import cv2 

font = cv2.FONT_HERSHEY_SIMPLEX 
lineType = cv2.LINE_AA 

im = cv2.imread('test/originals/8.jpg') 
im_ycrcb = cv2.cvtColor(im, cv2.COLOR_BGR2HSV) 

ball_ycrcb_mint = np.array([0, 90, 100],np.uint8) 
ball_ycrcb_maxt = np.array([25, 255, 255],np.uint8) 
ball_ycrcb = cv2.inRange(im_ycrcb, ball_ycrcb_mint, ball_ycrcb_maxt) 
cv2.imwrite('test/outputs/output8.jpg', ball_ycrcb) # Second image 
areaArray = [] 
count = 1 

_, contours, _ = cv2.findContours(ball_ycrcb, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 
for i, c in enumerate(contours): 
    area = cv2.contourArea(c) 
    areaArray.append(area) 
    areaLargest = np.argmax(areaArray) 
    areaLargestMax = max(areaArray) 
    areaLargestCnt = contours[areaLargest] 
    x, y, w, h = cv2.boundingRect(areaLargestCnt) 
    roi = im [y:y+h, x:x+w] 
    cv2.imwrite('test/contours.jpg', im) 
    if area == areaLargestMax and area > 10000: 
     cv2.drawContours(im, contours, i, (255, 0, 0), 7) 
     cv2.rectangle(im, (x, y), (x+w, y+h), (0,255,0), 7) 



cv2.imwrite('test/outputs/output9.jpg', im) 

答えて

2

あなただけの別の画像オブジェクトに矩形のROIを抽出し、imwriteを使用して、そのオブジェクトを保存することができます。

roi = im[y:y+h, x:x+w] 
cv2.imwrite("roi.jpg", roi) 
関連する問題