# -*- coding: utf-8 -*-
import cv2
import numpy as np
def Gray_img(src):
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
return gray
def threshold_img(src):
ret, binary = cv2.threshold(src, 20, 255, cv2.THRESH_BINARY)
return binary
imagepath = '/home/tao/1.jpg'
def rorate(imagepath):
img = cv2.imread(imagepath)
#image, contours, _ = cv2.findContours(img, 2, 2)
gray_img = Gray_img(img)
tresh_img = threshold_img(gray_img)
im2, contours, hierarchy = cv2.findContours(tresh_img, cv2.RETR_EXTERNAL , cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
# 最小外界矩形的宽度和高度
width, height = cv2.minAreaRect(cnt)[1]
if width* height > 100:
# 最小的外接矩形
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect) # 获取最小外接矩形的4个顶点
box = np.int0(box)
#cv2.drawContours(img, [box], 0, (255, 0, 255), 2)
if 0 not in box.ravel():
'''绘制最小外界矩形
for i in range(4):
cv2.line(image, tuple(box[i]), tuple(box[(i+1)%4]), 0) # 5
'''
# 旋转角度
theta = cv2.minAreaRect(cnt)[2]
print(theta)
if abs(theta) <= 45 and abs(theta)!=0:
print('图片的旋转角度为%s.'%theta)
angle = theta
# 仿射变换,对图片旋转angle角度
print(img.shape)
h, w,k= img.shape
center = (w//2, h//2)
M = cv2.getRotationMatrix2D(center, -angle, 1.0)
rotated = cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
cv2.imwrite('rotated.png', rotated)
rorate(imagepath)
opencv轮廓检测+最小外接矩形
原创
©著作权归作者所有:来自51CTO博客作者AI韬哥的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
openCV 画外接矩形 opencv最小外接矩形的角度
实验中使用到最小外接矩阵角度的内容,写博客记录。本篇主要参考了如下四个博客: &n
openCV 画外接矩形 opencv cv 旋转角度 顺时针