import cv2import numpy as npimport osfrom PIL import Imagedef calculate_psnrimg_path1 img_path2 # Load the images img1 = cv2imreadimg_path1 img2 = cv2imreadimg_path2 # Check if the images
I have made some modifications to the code to fix some errors and improve its functionality. Please find the updated code below:
import cv2 import numpy as np import os
def calculate_psnr(img_path1, img_path2): # Load the images img1 = cv2.imread(img_path1) img2 = cv2.imread(img_path2)
# Check if the images have the same size
if img1.shape != img2.shape:
# Resize the second image to match the size of the first image
img2 = cv2.resize(img2, (img1.shape[1], img1.shape[0]))
# Calculate the MSE of each channel
mse_r = np.mean((img1[:,:,0] - img2[:,:,0]) ** 2)
mse_g = np.mean((img1[:,:,1] - img2[:,:,1]) ** 2)
mse_b = np.mean((img1[:,:,2] - img2[:,:,2]) ** 2)
# Calculate the PSNR of each channel
psnr_r = 10 * np.log10((255 ** 2) / mse_r)
psnr_g = 10 * np.log10((255 ** 2) / mse_g)
psnr_b = 10 * np.log10((255 ** 2) / mse_b)
# Average the PSNR values
psnr_avg = (psnr_r + psnr_g + psnr_b) / 3
# Return the PSNR values
return psnr_avg, psnr_r, psnr_g, psnr_b
path1 = '/Users/tupengfei/Desktop/once/test' path2 = '/Users/tupengfei/Desktop/once/train'
Loop through all the image files in path1
for root, dirs, files in os.walk(path1): for file in files: # Check if the file is a JPEG image name, ets = os.path.splitext(file) if ets == '.jpg': # Loop through all the image files in path2 for root1, dirs1, files1 in os.walk(path2): for file1 in files1: # Check if the file is a JPEG image name1, ets1 = os.path.splitext(file1) if ets1 == '.jpg': # Calculate the PSNR between the two images psnr = calculate_psnr(os.path.join(root, file), os.path.join(root1, file1)) print('PSNR between', os.path.join(root, file), 'and', os.path.join(root1, file1), ':', psnr)
break
break
原文地址: https://www.cveoy.top/t/topic/bWP6 著作权归作者所有。请勿转载和采集!