count_env.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # @Time : 2024/6/13 0013 下午 12:03
  4. # @Author : liudan
  5. # @File : count_env.py
  6. # @Software: pycharm
  7. import cv2
  8. import os
  9. from PIL import Image, ImageDraw
  10. import numpy as np
  11. from skimage.metrics import structural_similarity as compare_ssim
  12. import json
  13. import random
  14. import yaml
  15. import demo_env
  16. from demo_env import registration_demo
  17. def compare_boxes_similarity(image1_path, image2_path, json_file_path, similarity_threshold=0.4):
  18. try:
  19. if not os.path.exists(image1_path):
  20. raise FileNotFoundError(f"Image file {image1_path} not found")
  21. image1 = Image.open(image1_path)# 原图尺寸,未resize
  22. image2 = wrap_image
  23. draw1 = ImageDraw.Draw(image1)
  24. # 存储相似度结果和是否相同的判断
  25. similarity_results = []
  26. same_content_boxes = []
  27. with open(json_file_path, 'r') as f:
  28. data = json.load(f)
  29. for shape in data['shapes']:
  30. if 'points' in shape:
  31. shape['points'] = [[int(round(x)), int(round(y))] for x, y in shape['points']]
  32. x1, y1 = shape['points'][0]
  33. x2, y2 = shape['points'][1]
  34. # 从两幅图像中截取对应区域
  35. region1 = image1.crop((x1, y1, x2, y2))
  36. # region1 = image1.crop((x1, y1, x2, y2)).convert('L')
  37. draw1.rectangle([x1, y1, x2, y2], outline='red', width=2)
  38. image1.save(os.path.join(params['save_dir'], f'save_annotated1_{i}.jpg'))
  39. region1.save(os.path.join(params['save_dir'], f'111111{i}.jpg'))
  40. # region2 = image2.crop((left-80, top, right-80, bottom))
  41. region2 = image2[y1:y2, x1:x2]
  42. # region2 = cv2.cvtColor(region2, cv2.COLOR_BGR2GRAY)
  43. # region2= region2.transpose(Image.FLIP_TOP_BOTTOM) #旋转180°针对pillowImage对象
  44. # region2 = cv2.rotate(region2, cv2.ROTATE_180)
  45. filename = f'json_image_{shape["label"]}_{i}.jpg'
  46. cv2.imwrite(os.path.join(params['save_dir'], filename), region2)
  47. cv2.rectangle(image2, (x1, y1), (x2, y2),(0,255,0), 2)
  48. cv2.imwrite(os.path.join(params['save_dir'], f'save_annotated2_{i}.jpg'), image2)
  49. # 将PIL图像转换为numpy数组,以便进行计算
  50. arr1 = np.array(region1)
  51. arr2 = region2 # region2一直是numpy数组,所以上述image1和image2处理方式不同
  52. # 确保两个数组的形状是相同的
  53. assert arr1.shape == arr2.shape, "Images do not have the same size for the given box"
  54. # 使用SSIM计算相似度(范围在-1到1之间,1表示完全相似)
  55. # ssim = compare_ssim(arr1, arr2, multichannel=False) # 这是旧版,可以计算灰度图相似度,对于计算彩色图像即使设置multichannel=True也错
  56. ssim = compare_ssim(arr1, arr2, channel_axis=2)
  57. similarity_results.append(ssim)
  58. if ssim > similarity_threshold:
  59. same_content_boxes.append(shape)
  60. cv2.rectangle(image2, (x1, y1), (x2, y2),(0,255,0), 2)
  61. text = "Similarity: " + str(round(ssim, 3))
  62. text_pos = (x1, y1 - 5)
  63. # 参数:图像, 文本, 文本位置, 字体类型, 字体大小, 字体颜色, 字体粗细
  64. cv2.putText(image2, text, text_pos, cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 255, 0), 2)
  65. cv2.imwrite(os.path.join(params['visualization_dir'],f'{wrap_images_name[:-8]}_{i}.jpg'), image2)
  66. else:
  67. cv2.rectangle(image2, (x1, y1), (x2, y2), (0, 0, 255), 2)
  68. text = "score: " + str(round(ssim, 3))
  69. text_pos = (x1, y1 - 5)
  70. # 参数:图像, 文本, 文本位置, 字体类型, 字体大小, 字体颜色, 字体粗细
  71. cv2.putText(image2, text, text_pos, cv2.FONT_HERSHEY_SIMPLEX, 1.5, (0, 0, 255), 2)
  72. cv2.imwrite(os.path.join(params['visualization_dir'], f'{wrap_images_name[:-8]}_{i}.jpg'), image2)
  73. return similarity_results, same_content_boxes
  74. except FileNotFoundError as e:
  75. print(f"An error occurred: {e}")
  76. except Exception as e:
  77. print(f"An unexpected error occurred: {e}")
  78. return None, None
  79. def read_params_from_yml(yml_file_path):
  80. with open(yml_file_path, 'r') as file:
  81. params = yaml.safe_load(file)
  82. return params
  83. if __name__ == "__main__":
  84. yml_file_path = 'params.yml'
  85. params = read_params_from_yml(yml_file_path)
  86. wrap_images_all = registration_demo(params['image_dir'],params['demo_image_path'], params['json_ref_path'], params['ref_image_path'])
  87. for i, item in enumerate(wrap_images_all):
  88. wrap_image,wrap_images_name = item
  89. similarity_results, same_content_boxes = compare_boxes_similarity(params['path_to_image1'], wrap_image, params['json_file_path'],
  90. params['similarity_threshold'])
  91. # 打印所有坐标框的相似度结果
  92. print(f"{wrap_images_name}\n")
  93. for idx, score in enumerate(similarity_results, 1):
  94. print(f"Similarity Score for Box {idx}: {score}")
  95. # 打印被认为是相同内容的坐标框
  96. print("Boxes with the same content:")
  97. for shape in same_content_boxes:
  98. print(shape['label'] + ' object is same as template')