在边界框外设置白色(Python,OpenCV)
Set white color outside boundingBox (Python, OpenCV)
我有这张图片:
(或这个..)
如何将 boundingBox 之外的所有区域设置为白色?
我想得到这个结果:
谢谢
取一个尺寸与图片尺寸相同的蒙版。掩码是一个值为 255(白色)的数组。我假设如果你正在绘制边界框,你肯定有每个边界框的坐标。对于每个边界框,您只需将蒙版中的区域替换为边界框所界定的区域,如下所示:
mask[y:y+h,x:x+w] = image[y:y+h,x:x+w]
,其中 mask
是具有所需结果的最终输出,image
是要进行处理的输入图像。两个图像的值 x
、y
、w
、h
是相同的,因为我们已确保蒙版和输入图像的尺寸相同。
如评论中所述,如果您有 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()
结果:
我有这张图片:
(或这个..)
如何将 boundingBox 之外的所有区域设置为白色?
我想得到这个结果:
谢谢
取一个尺寸与图片尺寸相同的蒙版。掩码是一个值为 255(白色)的数组。我假设如果你正在绘制边界框,你肯定有每个边界框的坐标。对于每个边界框,您只需将蒙版中的区域替换为边界框所界定的区域,如下所示:
mask[y:y+h,x:x+w] = image[y:y+h,x:x+w]
,其中 mask
是具有所需结果的最终输出,image
是要进行处理的输入图像。两个图像的值 x
、y
、w
、h
是相同的,因为我们已确保蒙版和输入图像的尺寸相同。
如评论中所述,如果您有 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()
结果: