在图像python中查找边数和每边的长度以及顶点数 [英] find number of sides and length of each side and number of vertices in image python
问题描述
我使用下面的代码来查找图像中的边数,但没有给出适当的结果导入cv2
I have used below code to find number of sides in an image but it's not giving appropriate result import cv2
image = cv2.imread('sheet.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
# Find contours and perform contour approximation
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.03 * peri, True)
print('number of sides:',len(approx))
此外,我想在图像中找到确切的边数和图像中每边的长度.下面是参考图片
Further i want to find exact number of side in an image and length of each side in the image . Below is the image for reference
除此之外,我们还可以得到每条边的长度,就像这里我们有 4 条边,所以相应边的长度和角的数量.
Along with this can we get the length of each side also like here we have 4 sides so the length of the respective side and the number of corners .
如果我们有任何形状的圆形或弧形,那么如何找到边的数量和长度
What if we have circular shape or arc in any shape, then how to find number of edges and it's length
推荐答案
这是在 Python/OpenCV 中使用 Canny 边缘实现此目的的一种方法.
Here is one way to do that in Python/OpenCV using Canny edges.
输入:
import cv2
import numpy as np
# load image
img = cv2.imread('quadrilateral.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# apply canny edge detection
edges = cv2.Canny(gray, 90, 130)
# apply morphology close
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
morph = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)
# get contours and keep largest
contours = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)
# draw contour
contour = img.copy()
cv2.drawContours(contour, [big_contour], 0, (0,0,255), 1)
# get number of vertices (sides)
peri = cv2.arcLength(big_contour, True)
approx = cv2.approxPolyDP(big_contour, 0.03 * peri, True)
print('number of sides:',len(approx))
# save results
cv2.imwrite("quadrilateral_edges.jpg", edges)
cv2.imwrite("quadrilateral_morphology.jpg", morph)
cv2.imwrite("quadrilateral_contour.jpg", contour)
# show result
cv2.imshow("edges", edges)
cv2.imshow("morph", morph)
cv2.imshow("contour", contour)
cv2.waitKey(0)
cv2.destroyAllWindows()
边缘图像:
形态图像(关闭边界):
Morphology image (to close boundary):
轮廓:
文本结果:
number of sides: 4
这篇关于在图像python中查找边数和每边的长度以及顶点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!