python - 如何找到对象(形状)的方向? - Python Opencv

标签 python opencv image-processing rotation

我的图像总是这样:
Original images

Original images

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

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

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

最佳答案

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

  • 阅读图片
  • 转换为灰度
  • 临界点
  • 获取外轮廓
  • 从外轮廓获取 minAreaRect 点和角度
  • 获取旋转矩形的顶点
  • 绘制旋转的矩形
  • 根据需要校正角度
  • 打印角度
  • 保存带有绘制在其上的旋转矩形的图像

  • 输入:
    enter image description here
    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 度
    带有旋转矩形的图像:
    enter image description here

    关于python - 如何找到对象(形状)的方向? - Python Opencv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58632469/

    相关文章:

    Python:如何打印UTF-8字符?

    python - 何时关闭/打开 MySQL 连接

    python - 在python OpenCV中以退出代码134(被信号6:SIGABRT中断)完成的过程

    c++ - 使用 OpenCV 从视频中提取图像模式的一些逻辑

    python - 如何每秒自动将视频帧的特定区域提取到图像文件中

    JAVA写入灰度JPEG图像(依赖JDK版本?)

    python - 选择滞后阈值

    Python 2.6 程序退出后不带换行符打印

    matlab - 使用 imwrite 保存 tif 32 位图像

    python - 清空变量而不销毁它