cv2.boundingRect()和cv2.rectangle()
cv2.boundingRect(img)这个函数可以获得一个图像的最小矩形边框一些信息,参数img是一个二值图像,它可以返回四个参数,左上角坐标,矩形的宽高,一般形式为:
x,y,w,h = cv2.boundingRect(img)
配合cv2.rectangle()可以画出该最小边框,cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)这个函数功能就是画框的函数。
举例说明:
例程
import cv2
o = cv2.imread('cs3.bmp')
cv2.imshow("original",o)
gray = cv2.cvtColor(o,cv2.COLOR_BGR2GRAY)
ret,binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
contours,hierarchy = cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
x,y,w,h = cv2.boundingRect(contours[0])
cv2.rectangle(o,(x,y),(x+w,y+h),(255,0,0),3)
aspectRatio = float(w)/h
print(aspectRatio)
cv2.imshow("result",o)
cv2.waitKey()
cv2.destoryAllWindows()
output: