使用 Opencv python 从图像中移除蒙版圆圈

Remove mask circle from image using Opencv python

我正在尝试使用 BitWish_not 移除图像的中心,但结果并不理想。看下面。

如您所见,它并没有删除所有颜色

下面是我的代码

image = cv2.imread("icons/agta.jpg")
height,width,depth = image.shape
circle = np.zeros((height,width), np.uint8)
cv2.circle(circle,(int(width/2),int(height/2)),90,1,thickness=-1)

masked = cv2.bitwise_not(image, image, mask=circle)

cv2.imshow("masked", masked)
cv2.imwrite("hue.jpg",masked)
cv2.waitKey(0) 

如果我理解这个问题,这是 Python/OpenCV

中的一种方法
  • 读取输入
  • 转换为灰色
  • 阈值
  • 应用形态学将其清洁为蒙版
  • 反转遮罩并制作 3 通道
  • 对输入应用掩码使圆变黑
  • 保存结果

输入:

import cv2
import numpy as np

# load image
img = cv2.imread('white_circle.jpg')

# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold input image
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

# apply morphology open and close and dilate
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
mask = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (55,55))
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
mask = cv2.morphologyEx(mask, cv2.MORPH_DILATE, kernel)

# invert mask
mask = 255 -mask

# make mask 3 channel
mask = cv2.merge([mask,mask,mask])

# apply mask to image to blacken circle area
result = img.copy()
result = cv2.bitwise_and(img, mask)

# save resulting masked image
cv2.imwrite('white_circle_thresh.jpg', thresh)
cv2.imwrite('white_circle_mask.jpg', mask)
cv2.imwrite('white_circle_masked.jpg', result)

# display result, though it won't show transparency
cv2.imshow("thresh", thresh)
cv2.imshow("mask", mask)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()


阈值图像:

蒙版图片:

输入中的黑圈: