【无标题】

import cv2  
import matplotlib.pyplot as plt  
from matplotlib.font_manager import FontProperties  

plt.rcParams['font.sans-serif'] = ['SimHei']    
plt.rcParams['axes.unicode_minus'] = False    
    
def count_and_draw_locks(image_path):   
    image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)  
    if image is None:  
        print(f"错误:无法加载位于 {image_path} 的图像")  
        return 0, None   
    blurred = cv2.GaussianBlur(image, (5, 5), 0)  
 
    _, thresh = cv2.threshold(blurred, 128, 255, cv2.THRESH_BINARY_INV)  

    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))  
    morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)  

    contours, _ = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)  
  
    lock_contours = [cnt for cnt in contours if 1000 < cv2.contourArea(cnt) < 100000]  
      
    output_image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)  
    cv2.drawContours(output_image, lock_contours, -1, (0, 255, 0), 2)  
      
    return len(lock_contours), output_image  
 
new_image_one_path = "D:\\P\\one.jpg"  
new_image_two_path = "D:\\P\\two.jpg"  
  
num_locks_one_adjusted, output_image_one = count_and_draw_locks(new_image_one_path)  
num_locks_two_adjusted, output_image_two = count_and_draw_locks(new_image_two_path)  

plt.figure(figsize=(15, 10))  

plt.subplot(1, 2, 1)  
plt.imshow(cv2.cvtColor(output_image_one, cv2.COLOR_BGR2RGB), cmap='gray')  
plt.title(f'图像1的轮廓(锁的数量:{num_locks_one_adjusted})')  
plt.xticks(range(0, output_image_one.shape[1], 50)) 
plt.yticks(range(0, output_image_one.shape[0], 50))  
plt.xlabel('X')  
plt.ylabel('Y')  
 
plt.subplot(1, 2, 2)  
plt.imshow(cv2.cvtColor(output_image_two, cv2.COLOR_BGR2RGB), cmap='gray')  
plt.title(f'图像2的轮廓(锁的数量:{num_locks_two_adjusted})')  
plt.xticks(range(0, output_image_two.shape[1], 50))  
plt.yticks(range(0, output_image_two.shape[0], 50))  
plt.xlabel('X')  
plt.ylabel('Y')  
  
plt.show()  

print(f"第一幅图像中的锁的数量:{num_locks_one_adjusted}")  
print(f"第二幅图像中的锁的数量:{num_locks_two_adjusted}")  

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值