Open vinhqngo5 opened 3 years ago
# Import libraries from matplotlib import pyplot as plt from scipy import spatial import numpy as np import cv2 as cv import os !pip install gdown
# Tải 2 bức ảnh cần so sánh !gdown --id 1NChSjvlcEnWwYUZAXHEDbqaDXWEU0IaB !gdown --id 1dA_XAXmUO4qC5ESgu8DCjTJmaHxqAzsj
# Hàm tính His def calculate_histogram (image_path, create_plot=False): img = cv.imread(image_path, 0) hist,bins = np.histogram(img.flatten(),256,[0,256]) cdf = hist.cumsum() cdf_normalized = cdf*float(hist.max())/cdf.max() if (create_plot == True): fig, axes = plt.subplots(1, 2) axes[1].plot(cdf_normalized, color = 'b') axes[1].hist(img.flatten(),256,[0,256,],color = 'r') axes[1].set_xlim([0,256]) axes[1].legend(('cdf','histogram'), loc = 'upper left') axes[0].imshow(img) axes[0].axis("off") fig.tight_layout() return plt, hist, bins else: return hist, bins # Tính size của ảnh def size(img): return img.shape[0] * img.shape[1] # Tính độ giống nhau giữa 2 ảnh def compare_2_images (image_path_1, image_path_2): # Return percentage of similarity img_1 = cv.imread(image_path_1, 0) img_2 = cv.imread(image_path_2, 0) hist_1, bins_1 = calculate_histogram(image_path_1) hist_2, bins_2 = calculate_histogram(image_path_2) size_1 = size(img_1) size_2 = size(img_2) result = 1 - spatial.distance.cosine(hist_1 / size_1, hist_2 / size_2) return result
# Tạo đường dẫn tới 2 ảnh folder_path = os.getcwd() image_path_1 = os.path.join(folder_path, "lena.jpg") image_path_2 = os.path.join(folder_path, "lena256.jpg") # Tạo histogram cho 2 hình plt_1, hist_1, bins_1 = calculate_histogram(image_path_1, True) plt_2, hist_2, bins_2 = calculate_histogram(image_path_2, True)
# test code function fancyAlert(arg) { if(arg) { $.facebox({div:'#foo'}) } }
Đỉnk
Phần 1: So sánh 2 ảnh Lena