import cv2
import numpy as np
o=cv2.imread('C:/Users/xpp/Desktop/coins.png')#原始图像
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)#计算图像轮廓
n=len(contours)
contoursImg=[]
for i in range(n):
temp=np.zeros(o.shape,np.uint8)
contoursImg.append(temp)
cnt=contours[i]
mask=np.zeros(gray.shape,np.uint8)
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)#绘制文本字符串
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()
leftmost= (173, 54) rightmost= (282, 68) topmost= (218, 10) bottommost= (222, 114)
算法:四个极点是图像的最左端、最右端、最上端、最下端的四个极值点。
注意:图像的极点不是最值点。
本文分享自 图像处理与模式识别研究所 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!