如何填充图像中的空洞

Eze*_*Sin 2 python opencv image

我在填充图像的内部漏洞时遇到了一些困难,非常感谢您的帮助。

在分散方面:

mlist_0 = movelist_porous[0]
rx = np.round(mlist_0[:,0])
ry = np.round(mlist_0[:,1])
fig, axs = plt.subplots(1,1,figsize=(12,8))
axs.scatter(mlist_0[:,0], mlist_0[:,1], color='black')
plt.axis('off')
# plt.savefig("test.png", bbox_inches='tight')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在情节方面:

mlist_0 = movelist_porous[0]
rx = np.round(mlist_0[:,0])
ry = np.round(mlist_0[:,1])
fig, axs = plt.subplots(1,1,figsize=(12,8))
axs.plot(mlist_0[:,0], mlist_0[:,1], color='black')
plt.axis('off')
plt.savefig("test.png", bbox_inches='tight')
plt.show()
Run Code Online (Sandbox Code Playgroud)

我想要这样的结果:

这些孔填充了一种颜色(黑色),周围的轮廓填充了另一种颜色(白色),但是,我不确定如何做到这一点。

amr*_*ras 5

在这里,从绘图中的图像开始。

import numpy as np
import cv2

# Reading the image saved from plot
image = cv2.imread('test.jpg')

# Coversion to grayscale, inversion, edge detection
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.bitwise_not(gray)
edges = cv2.Canny(gray, 50, 200)

# Find the contours. The first two largest contours are for the outer contour
# So, taking the rest of the contours for inner contours
cnts = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[2:]

# Filling the inner contours with black color
for c in cnts:
    cv2.drawContours(image, [c], -1, (0, 0, 0), -1)

# Displaying the result
cv2.imshow("Contour", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)

代码的输出:

在此处输入图片说明