![](/img/trans.png)
[英]How to determine object orientation in binary image? (Python, OpenCV)
[英]How to find the orientation of an object (shape)? - Python Opencv
这是 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()
带有旋转矩形的图像:
对于类似的任务,我多次使用这个python 库进行定向 object 检测。 这是一个可训练的神经网络,用于检测物体的位置和方向。 当您知道方向角度后,您可以使用 opencv 将 object 旋转到所需的角度。 您将需要 label 一些图像来训练网络。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.