© Fu Xianjun. All Rights Reserved.
练习1:实物凸包检测¶
import cv2
# 读取图片并转至灰度模式
img = cv2.imread('hand.png', 1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化
ret, binary = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY)
# 图片轮廓
contours, hierarchy = cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)
n=len(contours) #轮廓个数
contoursImg=[]
x=0 #初始化要绘制的轮廓索引
for i in range(n):
area = cv2.contourArea(contours[i])
if area>10000:
print(f"轮廓{i}的面积:\n{area}")
x=i
cnt = contours[x]
cv2.imshow("binary",binary)
#寻找凸包并绘制凸包(轮廓)
hull = cv2.convexHull(cnt)
cv2.polylines(img,[hull],True,(0,255,0),2)
cv2.drawContours(img,contours,x,(0,0,255), 3)
# 显示图片
cv2.imshow('line', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
练习2:实物凸缺陷检测¶
import cv2
import numpy as np
img = cv2.imread('hand.png')
blur=cv2.medianBlur(img,5)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray,60,255,cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(binary,
cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
n=len(contours) #轮廓个数
contoursImg=[]
x=0 #初始化要绘制的轮廓索引
for i in range(n):
area = cv2.contourArea(contours[i])
if area>10000:
print(f"轮廓{i}的面积:\n{area}")
x=i
cnt = contours[x]
hull = cv2.convexHull(cnt,returnPoints = False)
defects = cv2.convexityDefects(cnt,hull)
#print(defects)
for i in range(defects.shape[0]):
s,e,f,d = defects[i,0]
#print(s,e,f,d)
start = tuple(cnt[s][0]) # 得到的是索引,要再轮廓中选出来
end = tuple(cnt[e][0])
far = tuple(cnt[f][0])
#print(far ,end)
cv2.line(img,start,end,[0,0,255],2)
cv2.circle(img,far,5,[255,0,0],-1)
cv2.imshow('result',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
练习3:极点
import cv2
import numpy as np
o = cv2.imread('binaryhand.png')
o1 = cv2.imread("face.png")
o1 = cv2.resize(o1,(40,40))
#--------获取并绘制轮廓-----------------
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)
mask = np.zeros(gray.shape,np.uint8)
cnt=contours[0]
cv2.drawContours(mask,[cnt],0,255,-1)
#--------计算极值-----------------
leftmost = tuple(cnt[cnt[:,:,0].argmin()][0])
rightmost = tuple(cnt[cnt[:,:,0].argmax()][0])
topmost = tuple(cnt[cnt[:,:,1].argmin()][0])
bottommost = tuple(cnt[cnt[:,:,1].argmax()][0])
#--------计算极值-----------------
print("leftmost=",leftmost)
print("rightmost=",rightmost)
print("topmost=",topmost)
print("bottommost=",bottommost)
#--------绘制说明文字-----------------
font=cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(o,'A',leftmost, font, 1,(0,0,255),2)
o[284:324,229:269]=o1
cv2.putText(o,'B',rightmost, font, 1,(0,0,255),2)
cv2.putText(o,'C',topmost, font, 1,(0,0,255),2)
cv2.putText(o,'D',bottommost, font, 1,(0,0,255),2)
#--------绘制图像-----------------
cv2.imshow("result",o)
#--------释放窗口-----------------
cv2.waitKey()
cv2.destroyAllWindows()