# import cv2
# import os
# import pandas as pd
#
#
# def detect_features(patent_img, product_img):
#     # 初始化ORB检测器
#     orb = cv2.ORB_create()
#
#     # 寻找关键点和描述符
#     kp1, des1 = orb.detectAndCompute(patent_img, None)
#     kp2, des2 = orb.detectAndCompute(product_img, None)
#
#     # 创建 BFMatcher 对象
#     bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
#
#     # 匹配描述符
#     if des1 is not None and des2 is not None:
#         matches = bf.match(des1, des2)
#         # 按照距离排序
#         matches = sorted(matches, key=lambda x: x.distance)
#
#         # 计算匹配的平均距离
#         avg_distance = sum(match.distance for match in matches) / len(matches)
#         num_matches = len(matches)
#     else:
#         matches = []
#         avg_distance = float('inf')  # 如果没有匹配，设置为无穷大
#         num_matches = 0
#
#     return matches, avg_distance, num_matches
#
#
# def batch_detect(patent_image_path, product_images_folder, output_csv):
#     # 读取专利图片并转换为灰度图
#     if not os.path.exists(patent_image_path):
#         print(f"Patent image path does not exist: {patent_image_path}")
#         return
#
#     patent_img = cv2.imread(patent_image_path, cv2.IMREAD_GRAYSCALE)
#     if patent_img is None:
#         print(f"Failed to load patent image: {patent_image_path}")
#         return
#
#     # 准备结果列表
#     results = []
#
#     # 遍历产品图片文件夹
#     for filename in os.listdir(product_images_folder):
#         if filename.endswith(".png") or filename.endswith(".jpg") or filename.endswith(".jpeg"):
#             product_image_path = os.path.join(product_images_folder, filename)
#             if not os.path.exists(product_image_path):
#                 print(f"Product image path does not exist: {product_image_path}")
#                 continue
#
#             product_img = cv2.imread(product_image_path)
#             if product_img is None:
#                 print(f"Failed to load product image: {product_image_path}")
#                 continue
#
#             # 将产品图片转换为灰度图
#             product_img_gray = cv2.cvtColor(product_img, cv2.COLOR_BGR2GRAY)
#
#             # 检测特征
#             matches, avg_distance, num_matches = detect_features(patent_img, product_img_gray)
#
#             # 保存结果
#             results.append({
#                 'product_image': filename,
#                 'avg_distance': avg_distance,
#                 'num_matches': num_matches
#             })
#
#     # 保存结果到CSV
#     df = pd.DataFrame(results)
#     df.to_csv(output_csv, index=False)
#
#     print(f"Results saved to {output_csv}")
#
#
# # 使用示例
# # patent_image_path = rf'E:/方星钧/工作/temp/pattern/企业微信截图_17169558138503.png'
# # patent_image_path = rf'E:\方星钧\工作\temp\pattern/企业微信截图_17169558377464.png'
# # patent_image_path = 'E:\\方星钧\\工作\\temp\\pattern\\企业微信截图_17169558138503.png'
# patent_image_path = r"C:\test\resaved_image.png"
#
# product_images_folder = rf'E:\方星钧\工作\temp\product'
# output_csv = rf'./comparison_results.csv'
#
# batch_detect(patent_image_path, product_images_folder, output_csv)
#

#
# import cv2
# import os
#
# # 检查文件路径
# patent_image_path = 'E:/方星钧/工作/temp/pattern/企业微信截图_17169558138503.png'
# if not os.path.exists(patent_image_path):
#     print(f"Patent image path does not exist: {patent_image_path}")
# else:
#     print(f"Patent image path exists: {patent_image_path}")
#
# # 尝试读取图像
# patent_img = cv2.imread(patent_image_path, cv2.IMREAD_GRAYSCALE)
# if patent_img is None:
#     print(f"Failed to load patent image: {patent_image_path}")
# else:
#     print(f"Successfully loaded patent image: {patent_image_path}")
#
#     # 显示图像以确认读取正确
#     cv2.imshow('Patent Image', patent_img)
#     cv2.waitKey(0)
#     cv2.destroyAllWindows()
#
#
#
# from PIL import Image
# import cv2
# import os
#
# # 原始专利图像路径
# patent_image_path = r'E:\方星钧\工作\temp\pattern\企业微信截图_17169558138503.png'
# # 重新保存的图像路径
# new_image_path = r'E:\方星钧\工作\temp\pattern\resaved_image.png'
#
# # 使用 PIL 重新保存图像
# try:
#     patent_img = Image.open(patent_image_path)
#     patent_img.save(new_image_path)
#     print(f"Successfully resaved patent image: {new_image_path}")
# except Exception as e:
#     print(f"Failed to resave patent image: {patent_image_path}, error: {e}")
#
# # 尝试使用 OpenCV 读取重新保存的图像
# new_img = cv2.imread(new_image_path, cv2.IMREAD_GRAYSCALE)
# if new_img is None:
#     print(f"Failed to load resaved image: {new_image_path}")
# else:
#     print(f"Successfully loaded resaved image: {new_image_path}")
#
#     # 显示图像以确认读取正确
#     cv2.imshow('Resaved Image', new_img)
#     cv2.waitKey(0)
#     cv2.destroyAllWindows()
#
# from PIL import Image
# import cv2
# import os
#
# # 尝试使用不同的路径和格式
# original_path = r'E:\方星钧\工作\temp\pattern\企业微信截图_17169558138503.png'
# new_png_path = r'E:\方星钧\工作\temp\pattern\resaved_image.png'
# new_jpg_path = r'./resaved_image.jpg'
#
# # 使用 PIL 重新保存图像为不同格式和路径
# try:
#     patent_img = Image.open(original_path)
#     patent_img.save(new_png_path)
#     patent_img.save(new_jpg_path)
#     print(f"Successfully resaved patent image to PNG and JPG formats.")
# except Exception as e:
#     print(f"Failed to resave patent image: {original_path}, error: {e}")
#
# # 尝试使用 OpenCV 读取重新保存的图像（PNG 格式）
# new_img_png = cv2.imread(new_png_path, cv2.IMREAD_GRAYSCALE)
# if new_img_png is None:
#     print(f"Failed to load resaved PNG image: {new_png_path}")
# else:
#     print(f"Successfully loaded resaved PNG image: {new_png_path}")
#
#     # 显示图像以确认读取正确
#     cv2.imshow('Resaved PNG Image', new_img_png)
#     cv2.waitKey(0)
#     cv2.destroyAllWindows()
#
# # 尝试使用 OpenCV 读取重新保存的图像（JPG 格式）
# new_img_jpg = cv2.imread(new_jpg_path, cv2.IMREAD_GRAYSCALE)
# if new_img_jpg is None:
#     print(f"Failed to load resaved JPG image: {new_jpg_path}")
# else:
#     print(f"Successfully loaded resaved JPG image: {new_jpg_path}")
#
#     # 显示图像以确认读取正确
#     cv2.imshow('Resaved JPG Image', new_img_jpg)
#     cv2.waitKey(0)
#     cv2.destroyAllWindows()



from PIL import Image
import cv2
import os
import shutil
import matplotlib.pyplot as plt

# 原始专利图像路径
original_patent_image_path = r'E:\方星钧\工作\temp\pattern\11.png'
# 新的简单路径
test_directory = r'C:\test'
new_png_path = os.path.join(test_directory, 'p11.png')
new_jpg_path = os.path.join(test_directory, 'p11.jpg')

# 创建测试文件夹
os.makedirs(test_directory, exist_ok=True)

# 确保原始路径存在，并复制图像到新路径
try:
    shutil.copy(original_patent_image_path, test_directory)
    copied_image_path = os.path.join(test_directory, os.path.basename(original_patent_image_path))
    print(f"Successfully copied patent image to: {copied_image_path}")
except Exception as e:
    print(f"Failed to copy patent image: {original_patent_image_path}, error: {e}")

# 使用 PIL 重新保存图像为不同格式和路径
try:
    patent_img = Image.open(copied_image_path)
    patent_img.save(new_png_path)
    # 保存为JPEG格式时，如果图像有alpha通道，需要先去掉alpha通道
    patent_img.convert('RGB').save(new_jpg_path)
    print(f"Successfully resaved patent image to PNG and JPG formats.")
except Exception as e:
    print(f"Failed to resave patent image: {copied_image_path}, error: {e}")

# 尝试使用 PIL 读取并显示重新保存的图像（PNG 格式）
try:
    resaved_img_png = Image.open(new_png_path)
    resaved_img_png.show()
    print(f"Successfully loaded and displayed resaved PNG image using PIL.")
except Exception as e:
    print(f"Failed to load resaved PNG image using PIL: {new_png_path}, error: {e}")

# 尝试使用 OpenCV 读取重新保存的图像（PNG 格式）
new_img_png = cv2.imread(new_png_path, cv2.IMREAD_GRAYSCALE)
if new_img_png is None:
    print(f"Failed to load resaved PNG image using OpenCV: {new_png_path}")
else:
    print(f"Successfully loaded resaved PNG image using OpenCV: {new_png_path}")

    # 使用 Matplotlib 显示图像
    plt.imshow(new_img_png, cmap='gray')
    plt.title('Resaved PNG Image')
    plt.show()

# 尝试使用 OpenCV 读取重新保存的图像（JPG 格式）
new_img_jpg = cv2.imread(new_jpg_path, cv2.IMREAD_GRAYSCALE)
if new_img_jpg is None:
    print(f"Failed to load resaved JPG image using OpenCV: {new_jpg_path}")
else:
    print(f"Successfully loaded resaved JPG image using OpenCV: {new_jpg_path}")

    # 使用 Matplotlib 显示图像
    plt.imshow(new_img_jpg, cmap='gray')
    plt.title('Resaved JPG Image')
    plt.show()
