OpenCV,将对象划分为多个部分

时间:2013-11-21 07:27:25

标签: python opencv image-processing

我有以下图片:https://drive.google.com/file/d/0B6NhNcM1nZznQXVUZ01qS0Q3YTA/edit?usp=sharing

OpenCV(最好是Python)中是否有一个函数可以说这个图片中的对象可以分成几部分。例如,第一个对象由两个段(或两个行)组成,第三个由三个(或四个)组成。

如果OpenCV没有这样的东西,那么在任何地方都可以了解这样的算法/功能。

1 个答案:

答案 0 :(得分:2)

可以通过对图像进行骨架化然后使用HoughlinesP来解决此问题。 Scikit-image有一个很好的骨架化方法。 可以直接找到14个线段,如下所示。 最后,您将需要查看哪些线相交以查看哪些线组合在一起。

result

#!/usr/bin/python

from skimage import morphology
import cv2
import math
import numpy as np

im = cv2.imread("objects.png")
dst = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

dst = 1 - dst / 255
dst = morphology.skeletonize(dst).astype(np.uint8)

objs = 255 * dst

#cv2.HoughLinesP(image, rho, theta, threshold[, lines[, minLineLength[, maxLineGap]]])
rho = 1
theta = math.pi / 180
threshold = 1
minLineLength = 3
maxLineGap = 5

lines = np.ndarray([1, 1, 4, 4])
lines = cv2.HoughLinesP(dst, rho, theta, threshold, lines, minLineLength, maxLineGap)

lineColor = (0, 255, 0)  # red

for line in lines[0]:
        #print line
        cv2.line(im, (line[0], line[1]), (line[2], line[3]), lineColor, 1, 8)

#
#   Now you need to go through lines and find those that intersect
#   You will notice that some lines have small gaps where they should
#   join to a perpendicular line. Before find intersections you would 
#   need to make each line longer (just by adjusting the numbers in lines)
#   to get around this problem.
#

cv2.imshow('Objects', objs)
cv2.imshow('Lines', im)
cv2.imwrite('lines.png', im)

cv2.waitKey() 
cv2.destroyAllWindows()