contours, hier = cv2.findContours(img,mode,method)
1. img: 要寻找轮廓的图像
2. mode:轮廓的检索模式(四种)
1.cv2.RETR_EXTERNAL 表示只检测外轮廓
2.cv2.RETR_LIST 检测的轮廓不建立等级关系
3.cv2.RETR_CCOMP 建立两个等级的轮廓,上面的一层为外边界,里面的一层为内孔的边界信息。如果内孔内还有一个连通物体,这个物体的边界也在顶层
4.cv2.RETR_TREE 建立一个等级树结构的轮廓
3. method:轮廓的近似办法
cv2.CHAIN_APPROX_NONE存储所有的轮廓点,相邻的两个点的像素位置差不超过1,即max(abs(x1-x2),abs(y2-y1))==1。cv2.CHAIN_APPROX_SIMPLE压缩水平方向,垂直方向,对角线方向的元素,只保留该方向的终点坐标,例如一个矩形轮廓只需4个点来保存轮廓信息
返回值:
contours:一个列表,返回的轮廓
hier:一个ndarray, 每条轮廓对应的属性,
import cv2
import numpy as np
img = cv2.pyrDown(cv2.imread("G:/cj/7.jpg", cv2.IMREAD_UNCHANGED))
print("图片大小:",img.shape)
#高斯滤波
gray_img = cv2.GaussianBlur(img, (5, 5), 0)
#cv2.threshold (源图片, 阈值, 填充色, 阈值类型)
#二值化 返回第一个得到的阈值值,第二个就是阈值化后的图像。
ret, thresh = cv2.threshold(cv2.cvtColor(gray_img.copy(), cv2.COLOR_BGR2GRAY) , 127, 255, cv2.THRESH_BINARY)
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(gray_img, (x,y), (x+w, y+h), (0, 255, 0), 1)
center1=(int(x+w/2),int(y+h/2))
print("中心坐标:",center1)
cv2.circle(gray_img, center1, 1, (0,255,0), -1, 0)
# find minimum area
rect = cv2.minAreaRect(c)
#绘制过中心的的直线
cv2.line(gray_img, (int(rect[0][0]),int(rect[0][1])),(int(rect[0][0]),0), (0,255,0),2,4)
# calculate coordinates of the minimum area rectangle获取矩形四个点
box = cv2.boxPoints(rect)
# normalize coordinates to integers取整
box = np.int0(box)
# draw contours
print("四点坐标:",box)
if box[0][0]<=img.shape[1]/2:
angle=rect[2]
cv2.line(gray_img, (int((box[2][0]+box[1][0])/2),int((box[2][1]+box[1][1])/2)),(int(rect[0][0]),int(rect[0][1])), (0,255,0),2,4)
print("偏转角度:",angle)
else:
angle=90+rect[2]
cv2.line(gray_img, (int((box[2][0]+box[3][0])/2),int((box[2][1]+box[3][1])/2)),(int(rect[0][0]),int(rect[0][1])), (0,255,0),2,4)
print("偏转角度:",angle)
cv2.drawContours(gray_img, [box], 0, (0,0, 255), 1)
# 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)
text='Angle:'+str(round(angle,2))+'\n'+str((box[2][0]+box[0][0])/2)+','+str((box[2][1]+box[0][1])/2)
y0, dy = 50, 25
for i, txt in enumerate(text.split('\n')):
y = y0+2*i*dy
cv2.putText(gray_img, txt, (50,y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
cv2.drawContours(gray_img, contours, -1, (255, 0, 0), 1)
cv2.imshow("contours", gray_img)
cv2.waitKey()
cv2.destroyAllWindows()