python - 如何填充图像中的孔

标签 python image opencv

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

就散点而言:

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()

就情节而言:

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()

我想要这样的结果:

孔用一种颜色(黑色)填充,周围的轮廓用另一种颜色(白色)填充,但是,我不确定该怎么做。

最佳答案

开始吧,从图中的图像开始。

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()

代码的输出:

enter image description here

关于python - 如何填充图像中的孔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62482343/

相关文章:

c# - Windows Phone 8 LongListSelector 内的图像内存泄漏

python - 如何编写Xpath进行动态值传递?

python - 将 python 函数的输出从 STDOUT 重定向到 Python 中的变量

python - 获取系统 ping 的输出而不打印到控制台

python - Python中dict的元组列表

python - 我怎样才能从 url 中获取实时流?

c# - c# 中的 pictureBox.Image.Save() 不起作用

php - Codeigniter do_upload() 在 "success"上静默失败

python - 使用 Python 和 OpenCV3 检测流程图中的文本区域

c++ - 错误 : ‘cv::fisheye’ has not been declared