通过pHash算法实现相似图片检测的GUI界面python代码
时间: 2024-05-09 22:16:01 浏览: 134
以下是一个基于pHash算法的相似图片检测的GUI界面Python代码:
```python
import os
import sys
import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk
import imagehash
class App(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.select_button = tk.Button(self)
self.select_button["text"] = "Select Image"
self.select_button["command"] = self.select_image
self.select_button.pack(side="top")
self.compare_button = tk.Button(self)
self.compare_button["text"] = "Compare Images"
self.compare_button["command"] = self.compare_images
self.compare_button.pack(side="bottom")
def select_image(self):
self.filename = filedialog.askopenfilename(initialdir=os.getcwd(), title="Select Image", filetypes=(("jpeg files", "*.jpg"), ("png files", "*.png"), ("all files", "*.*")))
self.load_image()
def load_image(self):
self.image = Image.open(self.filename)
self.photo = ImageTk.PhotoImage(self.image)
self.image_label = tk.Label(image=self.photo)
self.image_label.pack(side="top")
def compare_images(self):
hash1 = imagehash.average_hash(self.image)
for filename in os.listdir(os.getcwd()):
if filename.endswith(".jpg") or filename.endswith(".png"):
image = Image.open(filename)
hash2 = imagehash.average_hash(image)
if hash1 - hash2 < 10:
result_label = tk.Label(text=filename + " is similar to " + self.filename)
result_label.pack(side="bottom")
root = tk.Tk()
app = App(master=root)
app.mainloop()
```
在这个GUI界面中,用户可以选择一个图像,然后点击“Compare Images”按钮,以与当前目录中的所有图像进行比较。如果找到一个与选定图像相似的图像,则会将其文件名显示在窗口底部。该算法使用平均哈希算法来计算图像的哈希值,并将哈希值之间的差异限制为10。这可以通过调整“< 10”语句中的值来更改。
阅读全文