def uqi_vif(path_true, path_pred): UQI = [] VIF = [] names = [] index = 1 files = list(glob(path_true + '/*.jpg')) + list(glob(path_true + '/*.png')) for fn in sorted(files): name = basename(str(fn)) names.append(name) img_gt = (imread(str(fn)) / 255.0).astype(np.float32) img_pred = (imread(path_pred + '/' + basename(str(fn))) / 255.0).astype(np.float32) img_gt = rgb2gray(img_gt) img_pred = rgb2gray(img_pred) UQI.append(uqi(img_gt, img_pred)) VIF.append(vifp(img_gt, img_pred)) if np.mod(index, 100) == 0: print( str(index) + ' images processed', "UQI: %.4f" % round(np.mean(UQI), 4), "VIF: %.4f" % round(np.mean(VIF), 4), ) index += 1 UQI = np.mean(UQI) VIF = np.mean(VIF) return UQI, VIF
def get_uiqi(img_batch, pert_batch): score = 0.0 for i in range(len(img_batch)): og_img = img_batch[i].data.cpu().permute(1, 2, 0).numpy() * 255.0 pert_img = pert_batch[i].data.cpu().permute(1, 2, 0).numpy() * 255.0 score += uqi(og_img, pert_img) return score
def mm(y1): t1, t2, t3, t4, t5, t6 = [], [], [], [], [], [] for i in range(32): t1.append(uqi(batch2[i + y1], d2[i + y1])) t2.append(mse(batch2[i + y1], d2[i + y1])) #t3.append(rmse(batch2[i],d2[i])) t6.append(vifp(batch2[i + y1], d2[i + y1])) #print("Structural Similarity Index (SSIM) is %0.3f" % np.mean(f)) # Good #print("Universal Quality Image Index (UQI) is %0.3f" % np.mean(t1)) # Good #print("Mean Squared Error (MSE) is %0.3f" % np.mean(t2) ) # Good #print("Visual Information Fidelity (VIF) is %0.3f" % np.mean(t6) ) # Good #print("Root Mean Sqaured Error (RMSE) is %0.3f" % np.mean(t3)) # Good #print("Spatial Correlation Coefficient (SCC) is %0.3f" % np.mean(t4) ) #print("Spectral Angle Mapper (SAM) is %0.3f" % np.mean(t5) ) return (np.mean(t1), np.mean(t2), np.mean(t6))
def obtain_similarity_metrics(GT_img, distorted_img): # MEAN SQUARED ERROR mse_value = mse(GT_img, distorted_img) # STRUCTURAL SIMILARITY ssim_value = ssim(GT_img, distorted_img) # PEAK SIGNAL TO NOISE RATIO psnr_value = psnr(GT_img, distorted_img) # ROOT MEAN SQUARED ERROR rmse_value = rmse(GT_img, distorted_img) # VISUAL INFORMATION FIDELITY vif_value = vifp(GT_img, distorted_img) # UNIVERSAL IMAGE QUALITY INDEX uqi_value = uqi(GT_img, distorted_img) # MULTI-SCALE STRUCTURAL SIMILARITY INDEX msssim_value = msssim(GT_img, distorted_img) # PSNR-HVS-M & PSNR-HVS p_hvs_m, p_hvs = psnrhmam.color_psnrhma(GT_img, distorted_img) return mse_value, ssim_value, psnr_value, rmse_value, vif_value, uqi_value, msssim_value, p_hvs_m, p_hvs
def MetricsCal(GT, P, scale): # c,w,h m1, GTmax = compute_psnr(GT, P) # bandwise mean psnr GT = GT.transpose(1, 2, 0) P = P.transpose(1, 2, 0) m2, _ = compute_sam(GT, P) # sam m3 = compute_ergas(GT, P, scale) from skimage.metrics import structural_similarity as ssim ssims = [] for i in range(GT.shape[2]): ssimi = ssim(GT[:, :, i], P[:, :, i], data_range=P[:, :, i].max() - P[:, :, i].min()) ssims.append(ssimi) m4 = np.mean(ssims) from sewar.full_ref import uqi m5 = uqi(GT, P) return np.float64(m1), np.float64(m2), m3, m4, m5
p1 = np.load(str(pathlib.Path(__file__).parent) + '/' + f + '/predictions.npy', allow_pickle=True) g1 = np.load(str(pathlib.Path(__file__).parent) + '/' + f + '/groundtruth.npy', allow_pickle=True) # p=np.load(str(pathlib.Path(__file__).parent)+'/sanitypredictions.npy',allow_pickle=True) # g=np.load(str(pathlib.Path(__file__).parent)+'/sanitygroundtruth.npy',allow_pickle=True) structsims = [] mses = [] mi = [] uqis = [] for point in range(len(p)): uqis.append(uqi(p[point].squeeze(), g[point])) structsims.append(structural_similarity(p[point].squeeze(), g[point])) mses.append(mse(p[point].squeeze(), g[point])) mi.append( sklearn.feature_selection.mutual_info_regression( p[point].squeeze().flatten().reshape(-1, 1), g[point].flatten())[0]) if parserargs.folder2: for point in range(len(p1)): uqis.append(uqi(p1[point].squeeze(), g1[point])) structsims.append(structural_similarity(p1[point].squeeze(), g1[point])) mses.append(mse(p1[point].squeeze(), g1[point])) mi.append( sklearn.feature_selection.mutual_info_regression( p1[point].squeeze().flatten().reshape(-1, 1),
def uqi_scores(): i = 0 for filename in os.listdir(with_coloration_path): i += 1 gt_name = filename[:filename.find( '_')] + '.png' # till the first occurence of underscore # print(gt_name) # print(gt_path + gt_name) gt_img = cv2.imread(gt_path + gt_name) im_path = with_coloration_path + filename inp_img = cv2.imread(im_path) predicted_path = get_path(inp_img, 117) # threshold=117 ws['A{}'.format(i + 1)] = filename ws['B{}'.format(i + 1)] = uqi(gt_img, inp_img) dehazenet_image = cv2.imread( dehazenet_coloration_path + '{}_finalWithoutCLAHE.jpg'.format(filename[:-4])) uqi_dehaze = uqi(gt_img, dehazenet_image) ws['C{}'.format(i + 1)] = uqi_dehaze if predicted_path == 1: ws['D{}'.format(i + 1)] = uqi( gt_img, apply_CLAHE(adaptive_enhance(inp_img))) else: ws['D{}'.format(i + 1)] = uqi_dehaze # Comparison with raw input image scores if ws['D{}'.format(i + 1)].value > ws['B{}'.format(i + 1)].value: ws['E{}'.format(i + 1)] = "Yes" elif ws['D{}'.format(i + 1)].value < ws['B{}'.format(i + 1)].value: ws['E{}'.format(i + 1)] = "No" else: ws['E{}'.format(i + 1)] = "Equal" # Comparison with DehazeNet scores if ws['D{}'.format(i + 1)].value > ws['C{}'.format(i + 1)].value: ws['F{}'.format(i + 1)] = "Yes" elif ws['D{}'.format(i + 1)].value < ws['C{}'.format(i + 1)].value: ws['F{}'.format(i + 1)] = "No" else: ws['F{}'.format(i + 1)] = "Equal" print("UQI computed for: ", filename) for filename in os.listdir(without_coloration_path): i += 1 gt_name = filename[:filename.find( '_')] + '.png' # till the first occurence of underscore gt_img = cv2.imread(gt_path + gt_name) im_path = without_coloration_path + filename inp_img = cv2.imread(im_path) predicted_path = get_path(inp_img, 117) # threshold=117 ws['A{}'.format(i + 1)] = filename ws['B{}'.format(i + 1)] = uqi(gt_img, inp_img) dehazenet_image = cv2.imread( dehazenet_without_coloration_path + '{}_finalWithoutCLAHE.jpg'.format(filename[:-4])) uqi_dehaze = uqi(gt_img, dehazenet_image) ws['C{}'.format(i + 1)] = uqi_dehaze if predicted_path == 1: ws['D{}'.format(i + 1)] = uqi( gt_img, apply_CLAHE(adaptive_enhance(inp_img))) else: ws['D{}'.format(i + 1)] = uqi_dehaze # Comparison with raw input image scores if ws['D{}'.format(i + 1)].value > ws['B{}'.format(i + 1)].value: ws['E{}'.format(i + 1)] = "Yes" elif ws['D{}'.format(i + 1)].value < ws['B{}'.format(i + 1)].value: ws['E{}'.format(i + 1)] = "No" else: ws['E{}'.format(i + 1)] = "Equal" # Comparison with DehazeNet scores if ws['D{}'.format(i + 1)].value > ws['C{}'.format(i + 1)].value: ws['F{}'.format(i + 1)] = "Yes" elif ws['D{}'.format(i + 1)].value < ws['C{}'.format(i + 1)].value: ws['F{}'.format(i + 1)] = "No" else: ws['F{}'.format(i + 1)] = "Equal" print("UQI computed for: ", filename) wb.save(excel_path) print("Script complete and excel saved!")
:returns: tuple -- ssim value, cs value. """ ssim_img = full_ref.ssim(ref_img, img, ws=11, K1=0.01, K2=0.03, MAX=None, fltr_specs=None, mode='valid') print("SSIM: structural similarity index = ", ssim_img) ############################################################################## #Universal image quality index """calculates universal image quality index (uqi). :param GT: first (original) input image. :param P: second (deformed) input image. :param ws: sliding window size (default = 8). :returns: float -- uqi value. """ UQI_img = full_ref.uqi(ref_img, img, ws=8) print("UQI: universal image quality index = ", UQI_img) ############################################################################## #Pixel Based Visual Information Fidelity (vif-p) """calculates Pixel Based Visual Information Fidelity (vif-p). :param GT: first (original) input image. :param P: second (deformed) input image. :param sigma_nsq: variance of the visual noise (default = 2) :returns: float -- vif-p value. """ VIFP_img = full_ref.vifp(ref_img, img, sigma_nsq=2) print("VIFP: Pixel Based Visual Information Fidelity = ", VIFP_img)
#save os.makedirs("test_data/fake_visible", exist_ok = True) cv2.imwrite("test_data/fake_visible/" + vis_path , fake_A[0][:,:,::-1] * 255) totol_metric_dict_matched = {"mse":0.0,"rmse":0.0,"uqi":0.0,"ssim":0.0,"psnr":0.0,"psnrb":0.0,"vifp":0.0} #参数指标 true_path = "test_data/visible" fake_path = "test_data/fake_visiblee" lenth = len(os.listdir(true_path)) for true_name,fake_name in zip(os.listdir(true_path),os.listdir(fake_path)): true = cv2.imread(os.path.join(true_path,true_name)) fake = cv2.imread(os.path.join(fake_path,fake_name)) metric_dict_matched = {"mse":mse(fake,true),"rmse":rmse(fake,true),"uqi":uqi(fake,true),"ssim":ssim(fake,true)[0] \ ,"psnr":psnr(fake,true),"psnrb":psnrb(fake,true),"vifp":vifp(fake,true)} for key,value in metric_dict_matched.items(): totol_metric_dict_matched[key] = totol_metric_dict_matched[key]+value for key,value in totol_metric_dict_matched.items(): totol_metric_dict_matched[key] /= lenth print(totol_metric_dict_matched) #path = ["train_data/" + method + "_infrared","train_data/" + method + "_visible"] path = [true_path,fake_path] fid_value = fid.calculate_fid_given_paths(path, inception_path = None, low_profile=False) print("FID: ", fid_value) print("done")
xwind = np.cos(3 * np.pi / 2 - 2 * np.pi / 360. * temp2[x - size:x + size, y - size:y + size]).values ywind = np.sin(3 * np.pi / 2 - 2 * np.pi / 360. * temp2[x - size:x + size, y - size:y + size]).values sample["xWind"] = np.multiply(temp, xwind) sample["yWind"] = np.multiply(temp, ywind) for v in variables: if v not in ["Wind_Speed", "Wind_Direction"]: sample[v] = met[v].sel({"time": timepoint})[x - size:x + size, y - size:y + size].values if not (np.isnan(list( sample.values())).any()) and len(list(sample.values())) > 0: c = len(means["MSE"]) + 1 means["MSE"].append(MSE(predictions[-c], groundtruth[-c])) means["UQI"].append(uqi(predictions[-c], groundtruth[-c])) means["SSIM"].append( structural_similarity(predictions[-c], groundtruth[-c])) means["MI"].append( sklearn.feature_selection.mutual_info_regression( predictions[-c].squeeze().flatten().reshape(-1, 1), groundtruth[-c].flatten())[0]) for v in sample.keys(): if np.isnan(sample[v].mean()): print("nan point") print(list(sample[v].flatten())) plt.imshow(predictions[-c]) plt.savefig("prediction.png") plt.imshow(groundtruth[-c]) plt.savefig("groundtruth.png") print(np.isnan(list(sample[v])).any())
from sewar.full_ref import uqi from sewar.full_ref import mse from sewar.full_ref import rmse_sw from sewar.full_ref import ergas from sewar.full_ref import scc from sewar.full_ref import rase from sewar.full_ref import sam from sewar.full_ref import msssim from sewar.full_ref import vifp img1 = cv2.imread("ssim/png_source.png") img2 = cv2.imread("ssim/png_sr.png") print("Metricas\n") uqi = uqi(img1, img2) print("uqi: ", uqi) psnr = psnr(img1, img2) print("psnr: ", psnr) ssim = ssim(img1, img2) print("ssim: ", ssim) mse = mse(img1, img2) print("mse: ", mse) rmse_sw = rmse_sw(img1, img2) # print("rmse_sw: ", rmse_sw) ergas = ergas(img1, img2)
def get_Q(origin_img, encrypted_img): return uqi(origin_img, encrypted_img)
cnt = 0 clean_dir = './facades/test_syn_clean/' result_dir = './facades/test_syn_ours_icip/' total_files = os.listdir(clean_dir) uqi_list = [] mse_list = [] vif_list = [] msssim_list = [] for i in total_files: f_name = str(i).split('.')[0] img_clean = cv2.imread(clean_dir + str(f_name) + '.jpg') img_pred = cv2.imread(result_dir + str(f_name) + '.png') uq = uqi(img_clean, img_pred) uqi_list.append(uq) ms = mse(img_clean, img_pred) mse_list.append(ms) vi = vifp(img_clean, img_pred) vif_list.append(vi) mss = msssim(img_clean, img_pred) msssim_list.append(mss) cnt += 1 print('Mean Our UQI ' + str(np.mean(uqi_list))) print('Mean Our MSE ' + str(np.mean(mse_list)))
if __name__ == '__main__': image_rain = cv2.imread('./demo-images/rain.png') image_clear = cv2.imread('./demo-images/clear.png') #------------------------VIF----------------- try: print(" vif : ", vif(image_rain, image_clear)) except IOError: print("check out image path") # ------------------------niqe----------------- try: rain = np.array( Image.open('./demo-images/rain.png').convert('LA'))[:, :, 0] clear = np.array( Image.open('./demo-images/clear.png').convert('LA'))[:, :, 0] print(" clear image niqe : ", niqe(rain)) print(" rain image niqe : ", niqe(clear)) except IOError: print("check out image path") # ------------------------psnr----------------- try: rain = np.array(Image.open('./demo-images/rain.png')) clear = np.array(Image.open('./demo-images/clear.png')) print(" uqi : ", uqi(clear, rain)) except IOError: print("check out image path")
def calc_uqi(img1, img2): return uqi(img1, img2)
def compute_UQI(self): """ Compute Universal Quality Image Index between two images """ self.UQI = uqi(self.I1, self.I2) return ()