使用 python 库填充图像中的穿孔形状?
Fill perforated shape in image using python libs?
我有 "perforation" 的黑白图像。穿孔程度可以不同
有什么"standard"方法可以把图形完全填满黑色,使它们更相似吗?
首选 Pillow 和 opencv,但 imagemagick 也可以。
您可以使用 image morphology(i.e: closing) 来实现。
import cv2
import numpy as np
if __name__ == '__main__':
# read image
image = cv2.imread('image.png',cv2.IMREAD_UNCHANGED)
# convert image to gray
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# ensure only black and white pixels exist
ret,binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)
# morphology works with white forground
binary = cv2.bitwise_not(binary)
# get kernel for morphology
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
# number of iterations depends on the type of image you're providing
binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel, iterations=3)
# get black foreground
binary = cv2.bitwise_not(binary)
cv2.imshow('image', binary)
cv2.waitKey(0)
cv2.destroyAllWindows()
我有 "perforation" 的黑白图像。穿孔程度可以不同
有什么"standard"方法可以把图形完全填满黑色,使它们更相似吗?
首选 Pillow 和 opencv,但 imagemagick 也可以。
您可以使用 image morphology(i.e: closing) 来实现。
import cv2
import numpy as np
if __name__ == '__main__':
# read image
image = cv2.imread('image.png',cv2.IMREAD_UNCHANGED)
# convert image to gray
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# ensure only black and white pixels exist
ret,binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)
# morphology works with white forground
binary = cv2.bitwise_not(binary)
# get kernel for morphology
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
# number of iterations depends on the type of image you're providing
binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel, iterations=3)
# get black foreground
binary = cv2.bitwise_not(binary)
cv2.imshow('image', binary)
cv2.waitKey(0)
cv2.destroyAllWindows()