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}")
【无标题】
最新推荐文章于 2024-11-09 14:57:55 发布