Please modify this script to load all images from a folder and report the SSIM for each…
- User
Please modify this script to load all images from a folder and report the SSIM for each of them as well as the average for each distortion. The function could take an input as to whether it should save the images or not.
import os import cv2 import numpy as np import tempfile from skimage.metrics import structural_similarity as ssim from scipy.ndimage.filters import gaussian_filter
Create output directory if it doesn’t exist
output_dir = 'C:/Users/Del Pin/Pexels/Animals/dogs/distorted_images' if not os.path.exists(output_dir): os.makedirs(output_dir)
def imcontrastc(I, amount): LUT = np.interp(np.arange(256), np.array([0, 64, 192, 256]), np.array([0, (0.25 - amount/4)*255, (0.75 + amount/4)*255, 255])).astype('uint8') J = cv2.LUT(I, LUT) return J
def imblurgauss(a, radius): return np.array([gaussian_filter(a[..., i], radius) for i in range(a.shape[-1])]).transpose(1, 2, 0)
def imcompressjpeg(I, quality): temp_file = tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) fname = temp_file.name
cv2.imwrite(fname, I, [int(cv2.IMWRITE_JPEG_QUALITY), quality]) J = cv2.imread(fname, cv2.IMREAD_COLOR) temp_file.close() return Jdef main(): # Read the image img = cv2.imread('C:/Users/Del Pin/Pexels/Animals/dogs/dogs10_160738.jpg', cv2.IMREAD_COLOR)
# Apply contrast modification contrast_img = imcontrastc(img, 0.55) # Set the amount value (e.g., 0.5) cv2.imwrite(os.path.join(output_dir, 'dogs10_160738_contrast.jpg'), contrast_img) # Apply Gaussian blur blurred_img = imblurgauss(img, 4) # Set the radius value (e.g., 2) cv2.imwrite(os.path.join(output_dir, 'dogs10_160738_blur.jpg'), blurred_img) # Apply JPEG compression jpeg_img = imcompressjpeg(img, 8) # Set the quality value (e.g., 80) cv2.imwrite(os.path.join(output_dir, 'dogs10_160738_jpeg.jpg'), jpeg_img) # Calculate and print SSIM for each distorted image ssim_c = ssim(img, contrast_img, multichannel=True) ssim_b = ssim(img, blurred_img, multichannel=True) ssim_j = ssim(img, jpeg_img, multichannel=True) print('SSIM (contrast change):', round(ssim_c, 3)) print('SSIM (Gaussian filter):', round(ssim_b, 3)) print('SSIM (JPEG compression):', round(ssim_j, 3))main()
- Assistant
Here's the modified script that loads all images from a folder and reports the SSIM for each of them, as well as the average for each distortion:
import os import cv2 import numpy as np import tempfile from skimage.metrics import structural_similarity as ssim from scipy.ndimage.filters import gaussian_filter # Create output directory if it doesn’t exist output_dir = 'C:/Users/Del Pin/Pexels/Animals/dogs/distorted_images' if not os.path.exists(output_dir): os.makedirs(output_dir) def imcontrastc(I, amount): LUT = np.interp(np.arange(256), np.array([0, 64, 192, 256]), np.array([0, (0.25 - amount/4)*255, (0.75 + amount/4)*255, 255])).astype('uint8') J = cv2.LUT(I, LUT) return J def imblurgauss(a, radius): return np.array([gaussian_filter(a[..., i], radius) for i in range(a.shape[-1])]).transpose(1, 2, 0) def imcompressjpeg(I, quality): temp_file = tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) fname = temp_file.name cv2.imwrite(fname, I, [int(cv2.IMWRITE_JPEG_QUALITY), quality]) J = cv2.imread(fname, cv2.IMREAD_COLOR) temp_file.close() return J def main(input_folder, save_images=False): ssim_c_total = 0 ssim_b_total = 0 ssim_j_total = 0 num_images = 0 for file in os.listdir(input_folder): filepath = os.path.join(input_folder, file) # Read the image img = cv2.imread(filepath, cv2.IMREAD_COLOR) # Apply contrast modification contrast_img = imcontrastc(img, 0.55) # Set the amount value (e.g., 0.5) # Apply Gaussian blur blurred_img = imblurgauss(img, 4) # Set the radius value (e.g., 2) # Apply JPEG compression jpeg_img = imcompressjpeg(img, 8) # Set the quality value (e.g., 80) if save_images: # Save distorted images cv2.imwrite(os.path.join(output_dir, file[:-4] + '_contrast.jpg'), contrast_img) cv2.imwrite(os.path.join(output_dir, file[:-4] + '_blur.jpg'), blurred_img) cv2.imwrite(os.path.join(output_dir, file[:-4] + '_jpeg.jpg'), jpeg_img) # Calculate and print SSIM for each distorted image ssim_c = ssim(img, contrast_img, multichannel=True) ssim_b = ssim(img, blurred_img, multichannel=True) ssim_j = ssim(img, jpeg_img, multichannel=True) print(f'SSIM for {file}:') print(' SSIM (contrast change):', round(ssim_c, 3)) print(' SSIM (Gaussian filter):', round(ssim_b, 3)) print(' SSIM (JPEG compression):', round(ssim_j, 3)) ssim_c_total += ssim_c ssim_b_total += ssim_b ssim_j_total += ssim_j num_images += 1 # Calculate and print average SSIM for each distorted image print('\nAverage SSIM for each distortion:') print(' SSIM (contrast change):', round(ssim_c_total / num_images, 3)) print(' SSIM (Gaussian filter):', round(ssim_b_total / num_images, 3)) print(' SSIM (JPEG compression):', round(ssim_j_total / num_images, 3)) input_folder = 'C:/Users/Del Pin/Pexels/Animals/dogs/original_images' save_images = True main(input_folder, save_images)To run the script, set
input_folderto the path of the folder containing the input images, setsave_imagestoTrueif you want to save the distorted images, and callmain(input_folder, save_images). - User
import os import cv2 import numpy as np import tempfile from skimage.metrics import structural_similarity as ssim from scipy.ndimage.filters import gaussian_filter
Create output directory if it doesn't exist
output_dir = 'C:/Users/Del Pin/Pexels/Animals/dogs/' if not os.path.exists(output_dir): os.makedirs(output_dir)
def imcontrastc(I, amount): LUT = np.interp(np.arange(256), np.array([0, 64, 192, 256]), np.array([0, (0.25 - amount/4)*255, (0.75 + amount/4)*255, 255])).astype('uint8') J = cv2.LUT(I, LUT) return J
def imblurgauss(a, radius): return np.array([gaussian_filter(a[..., i], radius) for i in range(a.shape[-1])]).transpose(1, 2, 0)
def imcompressjpeg(I, quality): temp_file = tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) fname = temp_file.name
cv2.imwrite(fname, I, [int(cv2.IMWRITE_JPEG_QUALITY), quality]) J = cv2.imread(fname, cv2.IMREAD_COLOR) temp_file.close() return Jdef main(input_folder, save_images=False): ssim_c_total = 0 ssim_b_total = 0 ssim_j_total = 0 num_images = 0
for file in os.listdir(input_folder): filepath = os.path.join(input_folder, file) # Read the image img = cv2.imread(filepath, cv2.IMREAD_COLOR) # Apply contrast modification contrast_img = imcontrastc(img, 0.55) # Set the amount value (e.g., 0.5) # Apply Gaussian blur blurred_img = imblurgauss(img, 4) # Set the radius value (e.g., 2) # Apply JPEG compression jpeg_img = imcompressjpeg(img, 8) # Set the quality value (e.g., 80) if save_images: # Save distorted images cv2.imwrite(os.path.join(output_dir, file[:-4] + '_contrast.jpg'), contrast_img) cv2.imwrite(os.path.join(output_dir, file[:-4] + '_blur.jpg'), blurred_img) cv2.imwrite(os.path.join(output_dir, file[:-4] + '_jpeg.jpg'), jpeg_img) # Calculate and print SSIM for each distorted image ssim_c = ssim(img, contrast_img, multichannel=True) ssim_b = ssim(img, blurred_img, multichannel=True) ssim_j = ssim(img, jpeg_img, multichannel=True) print(f'SSIM for {file}:') print(' SSIM (contrast change):', round(ssim_c, 3)) print(' SSIM (Gaussian filter):', round(ssim_b, 3)) print(' SSIM (JPEG compression):', round(ssim_j, 3)) ssim_c_total += ssim_c ssim_b_total += ssim_b ssim_j_total += ssim_j num_images += 1 # Calculate and print average SSIM for each distorted image print('\nAverage SSIM for each distortion:') print(' SSIM (contrast change):', round(ssim_c_total / num_images, 3)) print(' SSIM (Gaussian filter):', round(ssim_b_total / num_images, 3)) print(' SSIM (JPEG compression):', round(ssim_j_total / num_images, 3))input_folder = 'C:/Users/Del Pin/Pexels/Animals/dogs/' save_images = False main(input_folder, save_images)
Returns #To run the script, set input_folder to the path of the folder containing the input images, set save_images to True if you want to save the distorted images, and call main(input_folder, save_images). Traceback (most recent call last):
File "C:\Users\DELPIN~1\AppData\Local\Temp/ipykernel_22164/339721191.py", line 86, in main(input_folder, save_images)
File "C:\Users\DELPIN~1\AppData\Local\Temp/ipykernel_22164/339721191.py", line 49, in main contrast_img = imcontrastc(img, 0.55) # Set the amount value (e.g., 0.5)
File "C:\Users\DELPIN~1\AppData\Local\Temp/ipykernel_22164/339721191.py", line 21, in imcontrastc J = cv2.LUT(I, LUT)
error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\core\src\matrix.cpp:749: error: (-215:Assertion failed) m.dims >= 2 in function 'cv::Mat::Mat'
[ WARN:0@0.204] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp (239) cv::findDecoder imread_('C:/Users/Del Pin/Pexels/Animals/dogs/distorted_images'): can't open/read file: check file path/integrity
This is surprising to me as I don't seem to set C:/Users/Del Pin/Pexels/Animals/dogs/distorted_images as a directory anywhere in the code?
- Assistant
The warning you received is related to the "img" variable being empty (None). When the script iterates through the folder, it might read a file that is not an image, causing this issue. To fix this, you can add a condition to check if the "img" variable is not empty before proceeding with the rest of the script.
Also, your current
input_folderandoutput_dirhave the same paths. As a result, the script will attempt to process the distorted images it previously saved. I updated the paths to differentiate between the original and distorted image folders. Here's the updated version:def main(input_folder, save_images=False): ssim_c_total = 0 ssim_b_total = 0 ssim_j_total = 0 num_images = 0 for file in os.listdir(input_folder): filepath = os.path.join(input_folder, file) # Read the image img = cv2.imread(filepath, cv2.IMREAD_COLOR) # Check if the image is valid (not None) if img is not None: # Apply contrast modification contrast_img = imcontrastc(img, 0.55) # Set the amount value (e.g., 0.5) # Apply Gaussian blur blurred_img = imblurgauss(img, 4) # Set the radius value (e.g., 2) # Apply JPEG compression jpeg_img = imcompressjpeg(img, 8) # Set the quality value (e.g., 80) if save_images: # Save distorted images cv2.imwrite(os.path.join(output_dir, file[:-4] + '_contrast.jpg'), contrast_img) cv2.imwrite(os.path.join(output_dir, file[:-4] + '_blur.jpg'), blurred_img) cv2.imwrite(os.path.join(output_dir, file[:-4] + '_jpeg.jpg'), jpeg_img) # Calculate and print SSIM for each distorted image ssim_c = ssim(img, contrast_img, multichannel=True) ssim_b = ssim(img, blurred_img, multichannel=True) ssim_j = ssim(img, jpeg_img, multichannel=True) print(f'SSIM for {file}:') print(' SSIM (contrast change):', round(ssim_c, 3)) print(' SSIM (Gaussian filter):', round(ssim_b, 3)) print(' SSIM (JPEG compression):', round(ssim_j, 3)) ssim_c_total += ssim_c ssim_b_total += ssim_b ssim_j_total += ssim_j num_images += 1 # Calculate and print average SSIM for each distorted image print('\nAverage SSIM for each distortion:') print(' SSIM (contrast change):', round(ssim_c_total / num_images, 3)) print(' SSIM (Gaussian filter):', round(ssim_b_total / num_images, 3)) print(' SSIM (JPEG compression):', round(ssim_j_total / num_images, 3)) input_folder = 'C:/Users/Del Pin/Pexels/Animals/dogs/original_images' output_dir = 'C:/Users/Del Pin/Pexels/Animals/dogs/distorted_images' save_images = False main(input_folder, save_images)Now, the script should work correctly without the error message.