将边界框的内容保存为新图像 - opencv python

时间:2017-10-22 21:15:00

标签: python opencv

我正在尝试使用一个代码片段,该代码片段使用opencv来识别图像中最大的轮廓/对象。下面的代码成功创建了边界框,但是将边界框保存为单独图像的最佳方法是什么,因此我可以将图像中的最大对象存储为新的jpg文件。这是我正在使用的代码:

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)

1 个答案:

答案 0 :(得分:8)

您只需将矩形ROI提取到另一个图像对象中,然后使用imwrite保存该对象。

roi = im[y:y+h, x:x+w]
cv2.imwrite("roi.jpg", roi)