在boundingBox外设置白色(Python,OpenCV)

时间:2018-05-16 10:39:07

标签: python opencv bounding-box

我有这张图片:

src

(或者这个......)

src2

如何在boundingBox'es之外的所有区域设置为白色?

我想获得这个结果:

desired

由于

2 个答案:

答案 0 :(得分:2)

如评论中所述,如果您拥有ROI的位置,您可以使用它们将它们粘贴到具有与原始形状相同的白色背景的图像上。

import cv2
import numpy as np

image = cv2.imread(r'C:\Users\Desktop\rus.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
white_bg = 255*np.ones_like(image)

ret, thresh = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY_INV)
blur = cv2.medianBlur(thresh, 1)
kernel = np.ones((10, 20), np.uint8)
img_dilation = cv2.dilate(blur, kernel, iterations=1)
im2, ctrs, hier = cv2.findContours(img_dilation.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])
for i, ctr in enumerate(sorted_ctrs):
    # Get bounding box
    x, y, w, h = cv2.boundingRect(ctr)
    roi = image[y:y + h, x:x + w]
    if (h > 50 and w > 50) and h < 200:

        cv2.rectangle(image, (x, y), (x + w, y + h), (255, 255, 255), 1)        
        cv2.imshow('{}.png'.format(i), roi)

        #--- paste ROIs on image with white background 
        white_bg[y:y+h, x:x+w] = roi

cv2.imshow('white_bg_new', white_bg)
cv2.waitKey(0)
cv2.destroyAllWindows() 

结果:

enter image description here

答案 1 :(得分:1)

使用尺寸与图像相同的蒙版。蒙版是一个值为255(白色)的数组。我假设如果你正在绘制边界框,你肯定有每个边界的坐标。对于每个边界框,你只需将掩码中的区域替换为由边界框限定的区域,如下所示:

mask [y:y + h,x:x + w] = image [y:y + h,x:x + w],其中mask是你想要的结果的最终输出,而image是你的输入图像进行哪种处理。值x,y,w,h对于图像都是相同的,因为我们确保了蒙版和输入图像的尺寸相同。