将边界框的内容保存为新图像 - OpenCV Python。

6

我正在尝试使用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)
2个回答

17

您可以将矩形ROI提取到另一个图像对象中,并使用imwrite保存该对象。

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

-1

存储带有边界框的图像:

cv2.imwrite('output.jpg',input_image)   

例如:

输入图像:

enter image description here

已保存的图像:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接