问题遇到的现象和发生背景
左右倾斜图像 最小矩形框绘制正确
两种情况下 都得出w大于h angle大于0
原理上 根据下面的图 左斜应该w<h 右斜w>h angle在[-90,0)之间
问题相关代码,请勿粘贴截图
import cv2
import numpy as np
读取原图像
img = cv2.imread('C:/Users/1.png')
读取灰度图像
img1 = cv2.imread('C:/Users/1.png', 0)
使用中值滤波
img2 = cv2.medianBlur(img1, 15)
二值化
ret, thresh1 = cv2.threshold(img2, 127, 255, cv2.THRESH_BINARY)
形态学运算中的开运算(opening):先腐蚀再膨胀
kernel = np.ones((5, 5), np.uint8)
opening = cv2.morphologyEx(thresh1, cv2.MORPH_OPEN, kernel)
opening = ~opening
contours, hierarchy = cv2.findContours(opening, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img, [box], 0, (0, 0, 255), 2)
x, y, w, h = cv2.boundingRect(cnt) # (x,y)是旋转的边界矩形左上角的点,w ,h分别是宽和高
angle = int(rect[2])
print(angle)
print(w, h)
运行结果及报错内容
4
1014 327
我的解答思路和尝试过的方法
参考 https://blog.csdn.net/vansbred/article/details/112312409
我想要达到的结果
希望可以分辨出左右斜