opencvpython中canny边缘图像的填充

ndh0cuux  于 2021-07-13  发布在  Java
关注(0)|答案(3)|浏览(662)

我有一个图像,例如:

我用canny边缘检测器得到了这个图像:

如何填充此图像?我要边缘围起来的区域是白色的。我如何做到这一点?

gywdnpxw

gywdnpxw1#

在python/opencv中,可以通过获取轮廓并在黑色背景上绘制白色填充来实现这一点。
输入:

import cv2
import numpy as np

# Read image as grayscale

img = cv2.imread('knife_edge.png', cv2.IMREAD_GRAYSCALE)
hh, ww = img.shape[:2]

# threshold

thresh = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)[1]

# get the (largest) contour

contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)

# draw white filled contour on black background

result = np.zeros_like(img)
cv2.drawContours(result, [big_contour], 0, (255,255,255), cv2.FILLED)

# save results

cv2.imwrite('knife_edge_result.jpg', result)

cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果:

xtfmy6hx

xtfmy6hx2#

这不能回答问题。
这只是我对问题的一个补充,评论不允许代码和图像。
示例图像具有透明背景。因此,alpha通道提供您要查找的输出。在没有任何图像处理知识的情况下,您可以按如下方式加载图像并提取alpha通道:

import cv2

img = cv2.imread('base.png', cv2.IMREAD_UNCHANGED)
alpha = img[:,:,3]

cv2.imshow('', alpha); cv2.waitKey(0); cv2.destroyAllWindows()

ygya80vv

ygya80vv3#

形态学运算的结果相似

img=cv2.imread('base.png',0)
_,thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY)
rect=cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
dilation = cv2.dilate(thresh,rect,iterations = 5)
erosion = cv2.erode(dilation, rect, iterations=4)

相关问题