如何沿着对象中心画一条线

时间:2019-09-14 01:41:48

标签: python opencv image-processing

我想通过使用这两条线来测量香蕉的宽度。第一行是香蕉周围的轮廓:

第二行是香蕉的中间行:

正如您在图片中看到的那样,我尝试使用skeletonization方法,但是它有一些噪音并且线路没有连接(实际上有多条线路相互重叠)。我希望红线是没有噪音的单线,如下所示:

所以我可以从中计算宽度。

更新:现在我可以删除所有嘈杂的像素,结果看起来像这样:

no noisy banana

但是该行是不连续的,我需要一个连续的行。

我想要做这条红线的原因有点难以解释,但是我想通过画一条这样的垂直线来找到最长的宽度:

result

另一个更新:现在,我可以通过在壁橱两点画一条线来连接所有这些线,结果看起来像done

1 个答案:

答案 0 :(得分:0)

此答案说明了如何找到轮廓的最厚部分。此答案有四个步骤。您已经完成了其中一些步骤,为清楚起见,我将在此答案中重申它们。

第1步:检测骨骼

skeleton

import cv2
import numpy as np
import math

# Read image
src = cv2.imread('/home/stephen/Desktop/banana.png')
img = src.copy()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
mask = np.zeros_like(gray)

# Find contours in image
contours, _ = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[1]

# Draw skeleton of banana on the mask
img = gray.copy()
size = np.size(img)
skel = np.zeros(img.shape,np.uint8)
ret,img = cv2.threshold(img,5,255,0)
element = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
done = False
while( not done):
    eroded = cv2.erode(img,element)
    temp = cv2.dilate(eroded,element)
    temp = cv2.subtract(img,temp)
    skel = cv2.bitwise_or(skel,temp)
    img = eroded.copy() 
    zeros = size - cv2.countNonZero(img)
    if zeros==size: done = True
kernel = np.ones((2,2), np.uint8)
skel = cv2.dilate(skel, kernel, iterations=1)
skeleton_contours, _ = cv2.findContours(skel, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
largest_skeleton_contour = max(skeleton_contours, key=cv2.contourArea)

第2步:将轮廓拉长到图像的边缘

scipy to extend skeleton

# Extend the skeleton past the edges of the banana
points = []
for point in largest_skeleton_contour: points.append(tuple(point[0]))
x,y = zip(*points)
z = np.polyfit(x,y,7)
f = np.poly1d(z)
x_new = np.linspace(0, img.shape[1],300)
y_new = f(x_new)
extension = list(zip(x_new, y_new))
img = src.copy()
for point in range(len(extension)-1):
    a = tuple(np.array(extension[point], int))
    b = tuple(np.array(extension[point+1], int))
    cv2.line(img, a, b, (0,0,255), 1)
    cv2.line(mask, a, b, 255, 1)   
mask_px = np.count_nonzero(mask)

第3步:找到轮廓中各点之间的距离,仅查看跨过骨架线的距离

distances that cross the skeleton line

# Find the distance between points in the contour of the banana
# Only look at distances that cross the mid line
def is_collision(mask_px, mask, a, b):
    temp_image = mask.copy()
    cv2.line(temp_image, a, b, 0, 2)
    new_total = np.count_nonzero(temp_image)
    if new_total != mask_px: return True
    else: return False

def distance(a,b): return math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2)

distances = []
for point_a in cnt[:int(len(cnt)/2)]:
    temp_distance = 0
    close_distance = img.shape[0] * img.shape[1]
    close_points = (0,0),(0,0)
    for point_b in cnt:
        A, B = tuple(point_a[0]), tuple(point_b[0])
        dist = distance(tuple(point_a[0]), tuple(point_b[0]))
        if is_collision(mask_px, mask, A, B):
            if dist < close_distance:
                close_points = A, B
                close_distance = dist
    cv2.line(img, close_points[0], close_points[1], (234,234,123), 1)
    distances.append((close_distance, close_points))
    cv2.imshow('img',img)
    cv2.waitKey(1)    

第4步:找到最大距离:

maximum distance

max_thickness = max(distances)
a, b = max_thickness[1][0], max_thickness[1][1]
cv2.line(img, a, b, (0,255,0), 4)
print("maximum thickness = ", max_thickness[0])