首页 > 解决方案 > OpenCV:仅返回图像的选定区域并将其余区域返回为黑色

问题描述

我正在尝试选择图像的某个区域,并且已经成功。但是,还有另一个问题,所选区域与源图像不在同一个位置。这是关于它的可视化:

左图是我生成的区域。但它不在正确的位置,正如我在正确的图像中想要的那样。

这是我已经尝试过的简单代码:

import cv2
import NumPy as np

pic= cv2.imread('set.jpeg')
pic = cv2.resize(pic, dsize=(500, 400), interpolation=cv2.INTER_CUBIC)
gray=cv2.cvtColor(pic,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),5)
_,thres = cv2.threshold(blur, 100,250, cv2.THRESH_TOZERO)
res = cv2.Canny(thres, 100, 200, L2gradient=True)

circles = cv2.HoughCircles(res,cv2.HOUGH_GRADIENT,1,20,param1=200,param2=15,minRadius=80,maxRadius=100)

crops = []
for i in circles[0,:]:
    # draw the outer circle
    cv2.circle(pic,(int(i[0]),int(i[1])),int(i[2]),(255,255,255),2)
    i = i.astype(int)
    crop = res[i[1]-i[2]:i[1]+i[2], i[0]-i[2]:i[0]+i[2]]
    crop = np.pad(crop,[(101, ), (151, )], mode='constant')
    crops.append(crop)

result = np.concatenate((crops[0],res),axis=1)
cv2.imshow('Hole',result)

cv2.waitKey(0)
cv2.destroyAllWindows()

我想要像右图一样的结果(仅生成蓝色框图像)并将其余部分返回为黑色(如左图)。

有什么方法可以在我想要的正确位置获得结果吗?(如右图)谢谢!!

标签: pythonnumpyopencv-python

解决方案


该问题已通过创建蒙版并通过以下代码行组合前景和背景来解决:

import cv2
import numpy as np

pic= cv2.imread('Assets/set.jpeg')
pic = cv2.resize(pic, dsize=(500, 400), interpolation=cv2.INTER_CUBIC)
gray=cv2.cvtColor(pic,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),5)
_,thres = cv2.threshold(blur, 100,250, cv2.THRESH_TOZERO)
res = cv2.Canny(thres, 100, 250, L2gradient=True)

circles = cv2.HoughCircles(res,cv2.HOUGH_GRADIENT,1,20,param1=200,param2=15,minRadius=80,maxRadius=100)
circles = np.uint16(np.around(circles))

mask = np.full((res.shape[0], res.shape[1]), 1, dtype=np.uint8)  # mask is only 
clone = pic.copy()
for i in circles[0, :]:
    cv2.circle(mask, (i[0], i[1]), i[2], (255, 255, 255), -1)
    cv2.circle(clone, (i[0], i[1]), i[2], (255, 255, 255), 1)

# get first masked value (foreground)
fg = cv2.bitwise_or(res, res, mask=mask)

# get second masked value (background) mask must be inverted
mask = cv2.bitwise_not(mask)
background = np.full(res.shape, 255, dtype=np.uint8)
bk = cv2.bitwise_or(background, background, mask=mask)

# combine foreground+background
final = cv2.bitwise_or(fg, bk)

result = np.concatenate((res,final),axis=1)
cv2.imshow('Hole',result)
cv2.waitKey(0)
cv2.destroyAllWindows()

没有什么可问的了,我会结束这个问题。谢谢!!


推荐阅读