import cv2
import numpy as np
img = cv2.imread('./hello.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#二值化,注意有两个返回值,阈值和结果
thresh, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
contours, hierachy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
rect = cv2.minAreaRect(contours[1])
#cv2.drawContours(img, contours, 1, (0, 0, 255), 2)这一步可以画轮廓
#rect是一个Rotated Rect旋转的矩形,矩形的起始坐标xy,长宽,旋转角度
#注意box给的是小数,但坐标必须是整数,要转化一下
box = cv2.boxPoints(rect)
box = np.round(box).astype('int64')
cv2.drawContours(img, [newbox], 0, (0, 0, 255), 2)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
#最大
import cv2
import numpy as np
img = cv2.imread('./hello.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#二值化,注意有两个返回值,阈值和结果
thresh, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
contours, hierachy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
rect = cv2.minAreaRect(contours[1])
#cv2.drawContours(img, contours, 1, (0, 0, 255), 2)这一步可以画轮廓
#rect是一个Rotated Rect旋转的矩形,矩形的起始坐标xy,长宽,旋转角度
#注意box给的是小数,但坐标必须是整数,要转化一下
box = cv2.boxPoints(rect)
box = np.round(box).astype('int64')
cv2.drawContours(img, [box], 0, (0, 0, 255), 2)
#最大返回四个(xy((wh),此处操作为最大
x, y, w, h = cv2.boundingRect(contours[1])
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()