簡體   English   中英

將邊界框的內容保存為新圖像 - opencv python

[英]saving contents of bounding box as a new image - opencv python

我正在嘗試使用一個代碼片段,該代碼片段使用 opencv 來識別圖像中最大的輪廓/對象。 下面的代碼成功創建了邊界框,但是將邊界框另存為單獨圖像的最佳方法是什么,因此我可以將圖像中最大的 object 存儲為新的 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)

您可以將矩形ROI提取到另一個圖像對象中,並使用imwrite保存該對象。

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

要使用邊界框存儲圖像:

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

例如。 輸入圖像:

在此處輸入圖像描述

保存的圖像:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM