I want to write a function which is getting two images reference and encoded and evaluates the (R)MSE and PSNR for each component (R, G, B, Y, Cb, Cr). For that, I am extracting all components and then I am converting the RGB -> YCbCr. I want to calculate the (R)MSE and PSNR without using a built-in function.
import os, sys, subprocess, csv, datetime
from PIL import Image
############ Functions Definitions ############
# Extracts the values of the R, G, B components of each pixel in the input file and calculates the Y, Cb, Cr components returning a dictionary having a key tuple with the coordinates of
the pixes and values the values of each R, G, B, Y, Cb, Cr components
def rgb_calc(ref_file):
img = Image.open(ref_file)
width, height = img.size
print(width)
print(height)
rgb_dict = {}
for x in range (width):
for y in range(height):
r, g, b = img.load()[x, y]
lum = 0.299 * r + 0.587 * g + 0.114 * b
cb = 128 - 0.168736 * r - 0.331264 * g + 0.5 * b
cr = 128 + 0.5 * r - 0.418688 * g - 0.081312 * b
print("X {} Y {} R {} G {} B {} Y {} Cb {} Cr {}".format(x, y, r, g, b, lum, cb, cr))
rgb_dict[(x, y)] = (r, g, b, lum, cb, cr)
return rgb_dict
############ MAIN FUNCTION ############
r_img = sys.argv[1]
p_img = sys.argv[2]
ref_img = Image.open(r_img)
proc_img = Image.open(p_img)
resolution_ref = ref_img.size
resolution_proc = proc_img.size
if resolution_ref == resolution_proc:
ycbcr_ref = rgb_calc(r_img)
ycbcr_proc = rgb_calc(proc_img)
else:
exit(0)
I want to write a new function and eventually output the average PSNR for each component and an average for the whole image.
Is there a way to speed up my process?
Currently, the img.load()
is taking around 10-11 seconds per 8Mpx image and the creation of the dictionary additional 6 seconds. So only extracting these values and creating two dictionaries is taking already 32 seconds.