如何找到通过斑点质心的斑点的主轴? [英] How to find the principal axis of a blob which goes through the centroid of the blob?

查看:0
本文介绍了如何找到通过斑点质心的斑点的主轴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找出穿过斑点质心的斑点的主轴。我能够找到斑点的质心,但如何找到主轴?

以下是我尝试过的内容:

import cv2
import numpy as np

img = cv2.imread('skin6.jpg')

imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh2 = cv2.threshold(imgray, 155, 255, cv2.THRESH_BINARY_INV)

#find the maximum contour
contours, heir = cv2.findContours(thresh2, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
c = max(contours, key = cv2.contourArea)

tmpArea = np.zeros(img.shape)
cv2.drawContours(tmpArea,[c],0,(255, 255, 255),cv2.FILLED)

#centroid
M = cv2.moments(c)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])

cv2.circle(tmpArea, (cx, cy), 5, (0, 0, 255), -1)

cv2.imshow("tmpArea", tmpArea)
cv2.waitKey(0)

这些是我使用的图片:

我正期待着这样的事情。它应该与等高线正确连接: Expected

推荐答案

可以对检测到的等高线使用cv2.fitEllipseThere's an OpenCV tutorial on that topic.您可以得到拟合的椭圆的中心、两个轴的长度(请详细查看cv2.ellipse)和旋转角度。根据这些信息,只需要一些数学运算就可以让主轴通过中心。

以下是经过一些修改和添加的代码:

import cv2
import numpy as np

# Images
img = cv2.imread('images/1KXQA.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh2 = cv2.threshold(img_gray, 155, 255, cv2.THRESH_BINARY_INV)[1]
tmpArea = np.zeros(img.shape)

# Contours
contours = cv2.findContours(thresh2, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[0]
c = max(contours, key=cv2.contourArea)
cv2.drawContours(tmpArea,[c],0,(255, 255, 255),cv2.FILLED)

# Centroid
M = cv2.moments(c)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
cv2.circle(tmpArea, (cx, cy), 5, (0, 0, 255), -1)

# Ellipse
e = cv2.fitEllipse(c)
cv2.ellipse(tmpArea, e, (0, 255, 0), 2)

# Principal axis
x1 = int(np.round(cx + e[1][1] / 2 * np.cos((e[2] + 90) * np.pi / 180.0)))
y1 = int(np.round(cy + e[1][1] / 2 * np.sin((e[2] + 90) * np.pi / 180.0)))
x2 = int(np.round(cx + e[1][1] / 2 * np.cos((e[2] - 90) * np.pi / 180.0)))
y2 = int(np.round(cy + e[1][1] / 2 * np.sin((e[2] - 90) * np.pi / 180.0)))
cv2.line(tmpArea, (x1, y1), (x2, y2), (255, 255, 0), 2)

# Output
cv2.imshow('tmpArea', tmpArea)
cv2.waitKey(0)

输出如下:

----------------------------------------
System information
----------------------------------------
Platform:      Windows-10-10.0.16299-SP0
Python:        3.8.5
NumPy:         1.19.5
OpenCV:        4.5.1
----------------------------------------

这篇关于如何找到通过斑点质心的斑点的主轴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆