边界框、最小矩形区域和最小闭圆的轮廓:
找到一个正方形轮廓很简单 找不规则的、歪斜的以及旋转的形状可用OpencV的cv2.findContours函数。
import cv2
import numpy as np
img = cv2.pyrDown(cv2.imread("hammer.jpg", cv2.IMREAD_UNCHANGED))
ret, thresh = cv2.threshold(cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY) , 127, 255, cv2.THRESH_BINARY)
image, contours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
# find bounding box coordinates
x,y,w,h = cv2.boundingRect(c)
cv2.rectangle(img, (x,y), (x+w, y+h), (0, 255, 0), 2)
# find minimum area
rect = cv2.minAreaRect(c)
# calculate coordinates of the minimum area rectangle
box = cv2.boxPoints(rect)
# normalize coordinates to integers
box = np.int0(box)
# draw contours
cv2.drawContours(img, [box], 0, (0,0, 255), 3)
# calculate center and radius of minimum enclosing circle
(x,y),radius = cv2.minEnclosingCircle(c)
# cast to integers
center = (int(x),int(y))
radius = int(radius)
# draw the circle
img = cv2.circle(img,center,radius,(0,255,0),2)
cv2.drawContours(img, contours, -1, (255, 0, 0), 1)
cv2.imshow("contours", img)
cv2.waitKey()
cv2.destroyAllWindows()
结果:
加载图片后先进行阈值处理,由于原图为黑白图片所以阈值较为简单
计算简单的边界框:
x,y,w,h=cv2.boundingRect(c)
转化为框的坐标及宽度,再画出框:
cv.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
第二步计算出包围最小的矩形区域
rect = cv2.minAreaRect(c)
# calculate coordinates of the minimum area rectangle
box = cv2.boxPoints(rect)
# normalize coordinates to integers
box = np.int0(box)
注意计算所得的顶点坐标为浮点型的,像素坐标必须为整数,所以必须做一个转换,然后画出这个矩形,可以用cv2.drawContours函数来:
cv2.drawContours(img,[box],0,(0,0,255),3)
该函数的第二个参数接收一个保存着轮廓的数组,从而可以在一次操作中绘制一系列轮廓。第三个参数为所要绘制的轮廓的索引,-1为绘制所有的轮廓,否则只会绘制轮廓组中指定的轮廓
最后检查的边界轮廓为最小闭圆:
(x,y),radius = cv2.minEnclosingCircle(c)
# cast to integers
center = (int(x),int(y))
radius = int(radius)
cv2.minEnclosingCircle函数会返回一个二元组,第一个元素为圆心坐标组成的元组,第二个元素为圆的半径值。