我正在尝试存档,在某些输入图像(请参阅下面的第二张图片)中根据覆盖区域(请参阅下面的第一张图片)在图像的轮廓之间绘制一条线。对于此操作,我正在执行以下操作:
我的问题是,有没有更好的方法来做这个操作或者我如何优化这个问题?
import cv2
from scipy.spatial import distance
delta = 2
def create_final():
# Read images as grayscale
cover = cv2.imread('cover.png', cv2.IMREAD_GRAYSCALE)
layer = cv2.imread('1.png', cv2.IMREAD_GRAYSCALE)
# Find Counters in Cover image
coverContours = cv2.findContours(
cover, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
coverContours = coverContours[0] if len(
coverContours) == 2 else coverContours[1]
# Find contours in layer image
pointsContours = cv2.findContours(
layer, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
pointsContours = pointsContours[0] if len(
pointsContours) == 2 else pointsContours[1]
for coverContour in coverContours:
try:
# Point_list x,y coordinates for every points in Cover area
point_list = []
for pointsContour in pointsContours:
# Check this point inside of Cover Contour
((x, y), r) = cv2.minEnclosingCircle(pointsContour)
if (cv2.pointPolygonTest(coverContour, (int(x), int(y)), False)) == 1:
# If inside of contour append to list
point_list.append((int(x), int(y)))
# we find the points inside of cover area.
for point in point_list:
# Copy point_list to temp list
temp = point_list.copy()
# Remove point from temp list otherwise closest node will be itself.
temp.remove(point)
# Delta means connection number for one point.
for x in range(0, delta):
# Find the closest point
end_point = __closest_node(point, temp)
# Remove closest point from list.
temp.remove(end_point)
# Draw line from one point to closest one.
cv2.line(layer, point, end_point,
255, 5)
except:
print('')
cv2.imwrite('final.png', layer)
def __closest_node(node, nodes):
if len(nodes) == 0:
return node
else:
closest_index = distance.cdist([node], nodes).argmin()
return nodes[closest_index]
create_final()