pythonopencv图像形态,如何找到物体(形状)的方向? -Python Opencv

My images are always like this:

NxVRE.png

Sjief.png

But I need to rotate them to be like this:

6WeWT.png

la0yx.png

But to do that, I need to find the orientation of the object, knowing that the thinner part of the object has to be on the left side.

In summary, the images are wings and the start of the wing has to be on the left side and the end of the wing has to be on the right side.

I hope someone can give me a suggestion, I've tried a bunch of different strategies but with no good result so far.

解决方案

Here is one way in Python/OpenCV.

Read the image

Convert to grayscale

Threshold

Get outer contour

Get minAreaRect points and angle from outer contour

Get vertices of rotated rectangle

Draw the rotated rectangle

Correct the angle as needed

Print the angle

Save the image with the rotated rectangle drawn on it

Input:

iDvsy.png

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()

Angle Returned: 0.8814040422439575 deg

Image with Rotated Rectangle:

aljDm.png

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值