Widen_boundary/0_dist_between_two_area.py

67 lines
1.8 KiB
Python

# -*- coding: UTF-8 -*-
import cv2
import numpy as np
import skimage.exposure
'''
两个区域间最短距离
https://www.cnpython.com/qa/1329750
'''
# read image
img = cv2.imread('demo/73.png')
h, w = img.shape[:2]
# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# threshold to binary
thresh = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)[1]
# create zeros mask 2 pixels larger in each dimension
mask = np.zeros([h + 2, w + 2], np.uint8)
# floodfill white between two polygons at 240,240
ffimg = thresh.copy()
ffimg = cv2.floodFill(ffimg, mask, (240,240), 255)[1]
# apply distance transform
distimg = ffimg.copy()
distimg = cv2.distanceTransform(distimg, cv2.DIST_L2, 5)
# Maximum spacing between polygons is 2 * largest value in distimg
max = 2*np.amax(distimg)
print('maximum spacing:', max)
print('')
# convert to polar image using (any) point in the center 'hole' of distimg
polar = cv2.warpPolar(distimg, (360,360), (320,330), 250, cv2.INTER_CUBIC+cv2.WARP_POLAR_LINEAR)
# get maximum value along each row
polar_max = np.amax(polar, axis=1)
# find max and min values from row maximum values
max = 2*np.amax(polar_max)
min = 2*np.amin(polar_max)
print('maximum spacing:', max)
print('minimum spacing:', min)
# scale distance image for viewing
distimg = skimage.exposure.rescale_intensity(distimg, in_range='image', out_range=(0,255))
distimg = distimg.astype(np.uint8)
# scale polar image for viewing
polar = skimage.exposure.rescale_intensity(polar, in_range='image', out_range=(0,255))
polar = polar.astype(np.uint8)
# save image
cv2.imwrite('polygons_floodfill.png',ffimg)
cv2.imwrite('polygons_distance.png',distimg)
cv2.imwrite('polygons_distance_polar.png',polar)
# show the images
cv2.imshow("thresh", thresh)
cv2.imshow("floodfill", ffimg)
cv2.imshow("distance", distimg)
cv2.imshow("polar", polar)
cv2.waitKey(0)
cv2.destroyAllWindows()