【问题标题】:How to find the orientation of an object (shape)? - Python Opencv如何找到对象(形状)的方向? - Python Opencv
【发布时间】:2021-06-02 16:56:48
【问题描述】:

我的图像总是这样:

但我需要将它们旋转成这样:

但要做到这一点,我需要找到对象的方向,知道对象的较薄部分必须在左侧。 总之,图像是翅膀,翅膀的起点必须在左侧,翅膀的末端必须在右侧。

我希望有人能给我一个建议,我尝试了很多不同的策略,但到目前为止都没有好的结果。

【问题讨论】:

标签: python opencv image-processing rotation


【解决方案1】:

这是 Python/OpenCV 中的一种方式。

  • 阅读图片

  • 转为灰度

  • 阈值

  • 获取外轮廓

  • 从外轮廓获取 minAreaRect 点和角度

  • 获取旋转矩形的顶点

  • 画出旋转的矩形

  • 根据需要校正角度

  • 打印角度

  • 保存带有旋转矩形的图像


输入:

import cv2
import numpy as np

# load image as HSV and select saturation
img = cv2.imread("wing2.png")
hh, ww, cc = img.shape

# convert to gray
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold the grayscale image
ret, thresh = cv2.threshold(gray,0,255,0)

# find outer contour
cntrs = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]

# get rotated rectangle from outer contour
rotrect = cv2.minAreaRect(cntrs[0])
box = cv2.boxPoints(rotrect)
box = np.int0(box)

# draw rotated rectangle on copy of img as result
result = img.copy()
cv2.drawContours(result,[box],0,(0,0,255),2)

# get angle from rotated rectangle
angle = rotrect[-1]

# from https://www.pyimagesearch.com/2017/02/20/text-skew-correction-opencv-python/
# the `cv2.minAreaRect` function returns values in the
# range [-90, 0); as the rectangle rotates clockwise the
# returned angle trends to 0 -- in this special case we
# need to add 90 degrees to the angle
if angle < -45:
    angle = -(90 + angle)
 
# otherwise, just take the inverse of the angle to make
# it positive
else:
    angle = -angle

print(angle,"deg")

# write result to disk
cv2.imwrite("wing2_rotrect.png", result)

cv2.imshow("THRESH", thresh)
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

返回角度:0.8814040422439575 度

带有旋转矩形的图像:

【讨论】:

  • 如何回答“物体的较薄部分必须在左侧”?
  • "angle = rotrect[-1]":-1 的魔力从何而来?
  • @alx 只是返回元组的最后一项是角度。
【解决方案2】:

您必须计算主轴(它基于 PCA)。它可以让您很好地了解主要方向,然后您可以相应地旋转图像。

正如评论指出的那样,您现在必须测试薄部分是否位于图像的右侧,为此您使用质心/重心:如果质心位于边界框的左侧,那么机翼的方向很好。

这是完整的算法:

  • 计算主方向(主轴,使用 PCA 计算)
  • 根据主轴方向旋转图像。
  • 计算边界框和质心/重心
  • 如果质心在左侧,则您的图像方向正确,否则将其旋转 180°。

这是结果...

【讨论】:

  • 它没有。 PCA 将给出主要方向,由机翼的厚部分高度加权。必须执行另一个操作来回答它。
  • 我使用了自己的 Java 库。我确信所有这些操作都存在于 Python 中。
【解决方案3】:

我多次使用这个python library 进行面向对象检测,以完成类似的任务。这是一个可训练的神经网络,用于检测物体的位置和方向。当您知道方向角度后,您可以使用 opencv 将对象旋转到所需的角度。您需要标记一些图像来训练网络。

【讨论】:

    猜你喜欢
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 2018-12-01
    相关资源
    最近更新 更多