实现自动输入密码
This commit is contained in:
42
cv2_test.py
Normal file
42
cv2_test.py
Normal file
@@ -0,0 +1,42 @@
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#定义形状检测函数
|
||||
def ShapeDetection(img:cv2.typing.MatLike):
|
||||
contours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) #寻找轮廓点
|
||||
all_cont=len(contours)
|
||||
# print(f"all_cont:{all_cont}")
|
||||
boll_count=0
|
||||
for obj in contours:
|
||||
perimeter = cv2.arcLength(obj,True) #计算轮廓周长
|
||||
approx = cv2.approxPolyDP(obj,0.02*perimeter,True) #获取轮廓角点坐标
|
||||
# CornerNum = len(approx) #轮廓角点的数量
|
||||
# area = cv2.contourArea(obj) #计算轮廓内区域的面积
|
||||
# print(f"area:{area}, perimeter:{perimeter}, CornerNum:{CornerNum}")
|
||||
x, y, w, h = cv2.boundingRect(approx) #获取坐标值和宽度、高度
|
||||
# print(f"{x},{y},{x+w},{y+h}")
|
||||
img_obj=img[y:y+h,x:x+w]
|
||||
# print(img_obj)
|
||||
nonzero_num=np.count_nonzero(img_obj)
|
||||
percentage=nonzero_num/img_obj.size
|
||||
# print(f"nonzero_num:{nonzero_num},size={img_obj.size}, pos:{percentage}")
|
||||
# 通过计算图像白值的比例来判断实心还是空心
|
||||
if(percentage>0.55):
|
||||
boll_count+=1
|
||||
return (all_cont,boll_count)
|
||||
|
||||
def calc_boll_count(path:str):
|
||||
img = cv2.imread(path)
|
||||
imgGray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY) # 转为灰度图
|
||||
ret, binary = cv2.threshold(imgGray,60,255,cv2.THRESH_BINARY) # 转为二值图
|
||||
return ShapeDetection(binary) #形状检测
|
||||
|
||||
if __name__ == "__main__":
|
||||
ret=calc_boll_count("1.png")
|
||||
print(ret)
|
||||
ret=calc_boll_count("1644-440 172x27.png")
|
||||
print(ret)
|
Reference in New Issue
Block a user