コード例 #1
0
ファイル: test___main__.py プロジェクト: ChsHub/SSIM-PIL
def test_compare_ssim(image_0, image_1, GPU, tile_size):
    # Open images from test directory
    image_0 = Image.open(join(image_directory, test_images[image_0]))
    image_1 = Image.open(join(image_directory, test_images[image_1]))
    if image_0 == image_1:
        value = compare_ssim(image_0, image_1, tile_size, GPU)
        assert abs(value - 1.0) < 0.001
コード例 #2
0
async def on_message(message):
    try:
        url = message.attachments[0].url
        response = requests.get(url)
        imgSent = Image.open(BytesIO(response.content)).resize((371, 365))
        img = Image.open("Kiss gifs/image0.png")
        value = compare_ssim(img, imgSent)
        print(value)
        if value >= 0.3:
            await message.delete()
    except:
         pass
    '''
    except IndexError:
        urls = re.findall(r"(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])", message.content)
        print(urls[0])
        if urls:
            print("here")
            for i in range(1, len(urls) + 1):
                try:
                    response = requests.get(urls.group(i))
                    print(urls.group(i))
                    imgSent = Image.open(BytesIO(response.content)).resize((371, 365))
                    img = Image.open("Kiss gifs/image0.png")
                    value = compare_ssim(img, imgSent)
                    print(value)
                    if value >= 0.3:
                        await message.delete()
                        break
                        '''
    await bot.process_commands(message)
コード例 #3
0
def are_two_images_different(lhs, rhs, threshold=0.93, print_value=False):
    lhs = preprocess_images(lhs)
    rhs = preprocess_images(rhs)

    value = compare_ssim(lhs, rhs, GPU=False)
    if print_value:
        print(value)
    return value < threshold
コード例 #4
0
def ssim():
    image1 = Image.open("eva1.png")
    image2 = Image.open("eva2.png")
    value = compare_ssim(image1, image2)

    print('ssim:', value)

    return
コード例 #5
0
def calculate_ssim(image0_path, image1_path, use_gpu=True, resize_before_comparison=False):
    """Calculates SSIM based on two images"""
    # print("Processing:", image0path)
    image0 = Image.open(image0_path)
    image1 = Image.open(image1_path)
    if resize_before_comparison is True:
        image0 = image0.resize((512, 512))
        image1 = image1.resize((512, 512))
    return compare_ssim(image0, image1, GPU=use_gpu)
コード例 #6
0
def get_SSIM(target, ref):
    # numpy->PIL
    target = Image.fromarray(
        cv2.cvtColor(target.astype('uint8'), cv2.COLOR_BGR2RGB))
    ref = Image.fromarray(cv2.cvtColor(ref.astype('uint8'), cv2.COLOR_BGR2RGB))
    ssim = compare_ssim(target, ref)
    # target.show()
    # ref.show()
    return round(ssim, 2)
コード例 #7
0
def compare_images(imageA, imageB):
    #returns a float -1 to 1, 1 is perfect similarity
    compare = compare_ssim(img1, img2)

    #convert to percentage
    compare += 1
    compare = 2 - compare
    compare /= 2
    return compare * 100
コード例 #8
0
ファイル: generator.py プロジェクト: igorbob/video-mash-up
def get_max_ssi(image_1, video, skip=1):
    max_ssi = -1.0

    for frame in range(0, video.frame_count, skip):
        with Image.open(video.get_frame_path(frame)) as image_2:
            ssi = compare_ssim(image_1, image_2)
            if ssi > max_ssi:
                max_ssi = ssi
                matching_frame = frame
    return max_ssi, matching_frame
コード例 #9
0
def __imageSimilarity(image1_path, image2_path):
    """(NOT USED) Compares two images using SSIM. 
    
    The images must be JPG (TODO: Improve this to work with any of them). 
    We do not use it because facebook image URLs have expired.
    """    
    Image.open(image1_path).resize((224,224)).save(image1_path)
    Image.open(image2_path).resize((224,224)).save(image2_path)
    image1 = cv2.imread(image1_path)
    image2 = cv2.imread(image2_path)    
    # convert the images to grayscale
    image1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
    image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)    
    ssim_score = compare_ssim(image1,image2)  
    return ssim_score
コード例 #10
0
def main(args):
    augmentations = [
        add_random_rain, add_random_snow, add_random_fog, add_speed_blur
    ]
    test_files = read_test_files(args.kitti_raw, args.test_file_path)
    outlier_dir = os.path.join(args.save_dir, "outliers")
    if not os.path.exists(outlier_dir):
        os.makedirs(outlier_dir)
    num_outlier = 0

    # test_files = test_files[:5]

    # process files
    for idx, fname in enumerate(test_files):
        print("processing: {}/{}".format(idx + 1, len(test_files)))
        fh = open(fname, 'rb')
        img = pil.open(fh).convert('RGB')
        img_aug = copy.copy(img)
        apply_x = copy.copy(augmentations)
        random.shuffle(apply_x)
        #count = np.random.choice([0, 1, 2], p=[0.10, 0.45, 0.45])
        count = np.random.choice([0, 2], p=[0.10, 0.90])
        #count = np.random.choice([0, 1], p=[0.10, 0.90])
        if count != 0:
            for aug_fun in apply_x:
                img_aug = aug_fun(img_aug, seed=idx)
                count -= 1
                if count == 0:
                    break
        else:
            pass  # no augmentation applied

        ssim_score = compare_ssim(img, img_aug)
        if ssim_score < 0.40:
            num_outlier += 1
            new_fname = "{0:04d}".format(idx)
            new_fname = os.path.join(outlier_dir, new_fname + ".png")
        else:
            # write augmented sample on disk
            new_fname = fname.replace(args.kitti_raw, args.save_dir)
            if not os.path.exists(os.path.dirname(new_fname)):
                os.makedirs(os.path.dirname(new_fname))

        # print(new_fname)
        img_aug.save(new_fname)

    print("Number of outlier samples: {}".format(num_outlier))
    return
コード例 #11
0
def find_minimum(temp_path: str, img: Image, new_type: str) -> str:
    """
    Find optimal image quality using a binary search.
    :param temp_path:
    :param img:
    :param new_type:
    :return: Smallest image with specified quality
    """
    low, high = 36, 100  # 30, 100
    temp_file_path = ''
    target_value = get_max_perception(img.size)
    log_data = "\n" + str(img.size) + '\t' + str(target_value)

    while high > low:
        # Delete previous image
        if isfile(temp_file_path):
            remove(temp_file_path)

        # Create temporary image
        quality = (low + high) // 2
        temp_file_path = get_temp_image(quality=quality,
                                        image=img,
                                        temp_path=temp_path,
                                        new_type=new_type)
        # Open temporary image and compare to original
        with Image.open(temp_file_path) as temp_image:
            value = compare_ssim(img, temp_image, GPU=True)

        # Set up bounds for next iteration
        if value > target_value:
            high = quality - 1
        else:
            low = quality + 1

        # Log data
        log_data += '\n' + str(quality) + '\t' + str(value)

    # Write log data to file
    with open('quality+' + temp_file_path[-4:] + '.log', mode='a') as f:
        f.write(log_data + '\n')

    return temp_file_path
コード例 #12
0
def caculate_AtoB(folder_A):
	'''Caculate PSNR and SSIM of synthetic images'''
	out_file = open("acc_output.txt", "a")
	print("----------------------------------------folder:",folder_A,"---------------------------------------",file=out_file)
	#Get images paths
	real_paths = Path(folder_A).glob('*real_B.png')
	#open a txt file for recording
	# out_file = open("output.txt", "a")

	for real_path in real_paths:
		#real_B path
		real_in_str = str(real_path)
		#fake_B path
		fake_path = re.sub('\.png$', '', real_in_str)
		fake_path = re.sub('real_B','',fake_path)
		fake_in_str = fake_path + "fake_B.png"


		#product name
		product_name = re.search('S3A_(.*)SEN3',real_in_str).group(1)
		product_name = "S3A_" +product_name+ "SEN3"

		#read fake image
		#fake_in_str = re.sub(folder_A+'/',folder_A+'/binary_fake/',fake_in_str)
		print("fake",fake_in_str)
		print("real",real_in_str)

		fake = Image.open(fake_in_str)
		data_fake = np.asarray(fake)

		#read real image
		real = Image.open(real_in_str)
		data_real = np.asarray(real)

		print("------image: ", fake_in_str,"---------",file=out_file)
		#ssim
		ssim_value = compare_ssim(real, fake)
		print("ssim: ",ssim_value,file=out_file)
		PSNR_value = PSNR(data_real,data_fake)
		print("PSNR: ",PSNR_value,file=out_file)

	out_file.close()
コード例 #13
0
    res = hr_guide
    _,_,h,w = lr_guide.size()
    for iteration in range (1):
        res = s.forward(lr_guide, lr_output ,res)
        lr_output = F.interpolate(res, (h, w), mode='bilinear', align_corners=True)

        # y = np.transpose(np.squeeze(res.data.numpy()), (1, 2, 0))
        # y = y.astype(np.uint8)
        # y = Image.fromarray(y)  # numpy to image
        # y = y.resize((w, h))
        # y.show()  
        # lr_y = np.array(y)
        # lr_y = np.transpose(lr_y,(2,0,1))   
        # lr_y = torch.tensor(lr_y, dtype=torch.float32)
        # lr_y = lr_y.unsqueeze(0)
    image1 = Image.open('hr_hdr.jpg')
    image2 = np.transpose(np.squeeze(res.detach().numpy()), (1,2,0))
    image2 = Image.fromarray(image2.astype(np.uint8))
    ssim = compare_ssim(image1, image2)
    print("ssim =",ssim)
    print("psnr =",psnr(res,hr_label))

    res = torch.cat((hr_label,res,hr_guide), dim=3)
    print("res =", res.shape)
    res = np.transpose(np.squeeze(res.data.numpy()), (1, 2, 0))
    res = res.astype(np.uint8)
    res = Image.fromarray(res)  # numpy to image
    res.show()

コード例 #14
0
encryptImage = user.encrypt()

# cs得到加密图像,产生加密后的距离
cs = CS(encryptImage=encryptImage, TP=TP)
cs.CS1encryptI()  # 对来自用户的图片进行加密,等同于对图像I使用k加密
# cs.testdecryption() #测试函数
cs.Cs1Cs2Denoising()  # cs1和cs2去噪的全过程
decryptImageRe = cs.CS1decryptI()  # 得到cs1一次解密后的去噪图片

# 用户得到去噪后图片密文,然后进行解密
user.decrypt(decryptImageRe)

from SSIM_PIL import compare_ssim
from PIL import Image

image1 = Image.open('resimage/gray' + init.imagepath[4:])
image2 = Image.open('resimage/result' + init.imagepath[4:])
value = compare_ssim(image1, image2)
print("去噪图像和源图像的SSIM是", value)

# import tensorflow as tf
#
# im1 = tf.decode_png('img/' + init.imagepath[4:])
# im2 = tf.decode_png('resimage/' + init.imagepath[4:])
# # Compute SSIM over tf.uint8 Tensors.
# ssim1 = tf.image.ssim(im1, im2, max_val=255, filter_size=11,
#                       filter_sigma=1.5, k1=0.01, k2=0.03)
# print("去噪图像和源图像的SSIM是", ssim1)

# user.test()
コード例 #15
0
def ssim(a, b):
    a = Image.open(a)
    b = Image.open(b)
    print(np.round(compare_ssim(a, b), 4))
    return np.round(compare_ssim(a, b), 4)
コード例 #16
0
import sys
import os
import warnings

#You may have to install SSIM_PIL from
#https://github.com/mmertama/SSIM-PIL.git
#as that wont show they annoying warning
#about pyopencl windows (also on OSX)
#even the GPU=FALSE as below

from SSIM_PIL import compare_ssim
from PIL import Image

if __name__ == '__main__':
    p1 = sys.argv[1]
    p2 = sys.argv[2]
    if not os.path.exists(p1):
        sys.exit("No found: " + p1)
    if not os.path.exists(p2):
        sys.exit("No found: " + p2)
    image1 = Image.open(p1)
    image2 = Image.open(p2)
    value = compare_ssim(image1, image2, GPU=False)
    print(value)

コード例 #17
0
for m, n in numbers:
    file_blur_up = folder + "/" + '%d_%d_blur_upsampling.png' % (int(m),
                                                                 int(n))
    file_cv_ref = folder + "/" + '%d_%d_cv_refinement.png' % (int(m), int(n))
    file_gt = folder + "/" + '%d_%d_GT.png' % (int(m), int(n))
    file_sequ = folder + "/" + '%d_%d_sequential.png' % (int(m), int(n))
    file_sequ_app = folder + "/" + '%d_%d_sequential_aperture.png' % (int(m),
                                                                      int(n))

    blur_up = Image.open(file_blur_up)
    cv_ref = Image.open(file_cv_ref)
    gt = Image.open(file_gt)
    sequ = Image.open(file_sequ)
    sequ_app = Image.open(file_sequ_app)

    ssims_blur_up.append(compare_ssim(gt, blur_up))
    ssims_cv_ref.append(compare_ssim(gt, cv_ref))
    ssims_sequ.append(compare_ssim(gt, sequ))
    ssims_sequ_app.append(compare_ssim(gt, sequ_app))
    #%%
print("mean SSIM blur upsampling = %f (std dev %f)" %
      (np.mean(ssims_blur_up), np.std(ssims_blur_up)))
print("mean SSIM CV refinement = %f (std dev %f)" %
      (np.mean(ssims_cv_ref), np.std(ssims_cv_ref)))
print("mean SSIM blur sequ = %f (std dev %f)" %
      (np.mean(ssims_sequ), np.std(ssims_sequ)))
print("mean SSIM blur sequ app = %f (std dev %f)" %
      (np.mean(ssims_sequ_app), np.std(ssims_sequ_app)))


#%%
コード例 #18
0
                          normalize=True)
        vutils.save_image(fake_B,
                          os.path.join(results_path,
                                       '%s_fake_B.jpg' % str(i).zfill(6)),
                          padding=0,
                          nrow=1,
                          normalize=True)

        loss = criterion(fake_B, data_B)
        psnr = 10 * math.log10(2**2 / loss.item())

        data_B_Img = Image.open(
            os.path.join(results_path, '%s_data_B.jpg' % str(i).zfill(6)))
        fake_B_Img = Image.open(
            os.path.join(results_path, '%s_fake_B.jpg' % str(i).zfill(6)))
        ssim = compare_ssim(data_B_Img, fake_B_Img)
        pa = compute_PA(data_B_Img, fake_B_Img)
        iou = compute_MIoU(data_B_Img, fake_B_Img)

        list_loss.append(loss.item())
        list_psnr.append(psnr)
        list_ssim.append(ssim)
        list_pa.append(pa)
        list_iou.append(iou)

        print('[%2d/%d]\tpsnr: %.4f\tssim: %.4f\tpa: %.4f\tiou: %.4f' %
              (i, len(dataloader), psnr, ssim, pa, iou))

    avg_psnr = sum(list_psnr) / len(list_psnr)
    avg_ssim = sum(list_ssim) / len(list_ssim)
    avg_pa = sum(list_pa) / len(list_pa)
コード例 #19
0
def distance_diff_size_plot(images_sentinel, images_naip):

    #right location experiment

    MSE_global_r = []
    SSIM_global_r = []

    for i in range(0, 20):
        #print(i)
        drone_url = images_sentinel[i]
        planet_url = images_naip[i]
        location = "TRUE"
        #response = requests.get(drone_url)
        drone_img = Image.open(drone_url)
        planet_img = Image.open(planet_url)
        planet_img = planet_img.convert('RGB')
        drone_img = drone_img.resize((512, 512))
        base_planet_img = planet_img.resize((512, 512))

        x_1 = []
        for i in range(1, 43):
            num = 12 * i
            if (num % 2) != 0:
                num = num + 1
            x_1.append(num)
            if i == 42:
                x_1.append(512)
        #print(x_1)

        if location == "TRUE":
            MSE_tt = []
            SSIM_tt = []
            for i in range(0, 43):
                if i in range(0, 42):
                    #print(i)
                    width = x_1[i] / 2
                    #print(width)
                    cropped_drone_img = drone_img.crop(
                        (256 - width, 256 - width, 256 + width, 256 + width))
                    #print("size",cropped_drone_img.size)
                    cropped_drone_img = drone_img.crop(
                        (256 - width, 256 - width, 256 + width,
                         256 + width)).resize((512, 512))
                    cropped_planet_img = base_planet_img.crop(
                        (256 - width, 256 - width, 256 + width,
                         256 + width)).resize((512, 512))
                    np_drone = np.array(cropped_drone_img)
                    np_planet = np.array(cropped_planet_img)
                    MSE = metrics.mean_squared_error(np_drone.flatten(),
                                                     np_planet.flatten())
                    MSE_tt.append(MSE)
                    SSIM = compare_ssim(cropped_drone_img, cropped_planet_img)
                    SSIM_tt.append(SSIM)
                else:
                    #print(i, "after 500")
                    if i == 43:
                        cropped_drone_img = cropped_drone_img.resize(
                            (512, 512))
                        cropped_planet_img = base_planet_img.resize((512, 512))
                    cropped_drone_img = cropped_drone_img.resize(
                        (i * 12, i * 12))
                    cropped_planet_img = base_planet_img.resize(
                        (i * 12, i * 12))
                    #print(cropped_planet_img.size)
                    np_drone = np.array(cropped_drone_img)
                    np_planet = np.array(cropped_planet_img)
                    MSE = metrics.mean_squared_error(np_drone.flatten(),
                                                     np_planet.flatten())
                    MSE_tt.append(MSE)
                    SSIM = compare_ssim(cropped_drone_img, cropped_planet_img)
                    SSIM_tt.append(SSIM)
            #print(len(MSE_global_r))
            SSIM_global_r.append(SSIM_tt)
            MSE_global_r.append(MSE_tt)

    #wrong location experiment

    import random

    location = "WRONG"

    MSE_global_wl = []
    SSIM_global_wl = []

    def rotate(l, n):
        return l[n:] + l[:n]

    for i in range(0, 20):
        drone_url = images_sentinel[i]
        images_naip_rot = rotate(images_naip, 2)
        planet_url = images_naip_rot[i]
        drone_img = Image.open(drone_url)
        planet_img = Image.open(planet_url)
        planet_img = planet_img.convert('RGB')
        drone_img = drone_img.resize((512, 512))
        base_planet_img = planet_img.resize((512, 512))

        x_1 = []
        for i in range(1, 43):
            num = 12 * i
            if (num % 2) != 0:
                num = num + 1
            x_1.append(num)
            if i == 42:
                x_1.append(512)

        if location == "WRONG":
            MSE_tt = []
            SSIM_tt = []
            for i in range(0, 43):
                if i in range(0, 42):
                    width = x_1[i] / 2
                    cropped_drone_img = drone_img.crop(
                        (256 - width, 256 - width, 256 + width, 256 + width))
                    cropped_drone_img = drone_img.crop(
                        (256 - width, 256 - width, 256 + width,
                         256 + width)).resize((512, 512))
                    cropped_planet_img = base_planet_img.crop(
                        (256 - width, 256 - width, 256 + width,
                         256 + width)).resize((512, 512))
                    np_drone = np.array(cropped_drone_img)
                    np_planet = np.array(cropped_planet_img)
                    MSE = metrics.mean_squared_error(np_drone.flatten(),
                                                     np_planet.flatten())
                    MSE_tt.append(MSE)
                    SSIM = compare_ssim(cropped_drone_img, cropped_planet_img)
                    SSIM_tt.append(SSIM)
                else:
                    if i == 43:
                        cropped_drone_img = cropped_drone_img.resize(
                            (512, 512))
                        cropped_planet_img = base_planet_img.resize((512, 512))
                    cropped_drone_img = cropped_drone_img.resize(
                        (i * 12, i * 12))
                    cropped_planet_img = base_planet_img.resize(
                        (i * 12, i * 12))
                    np_drone = np.array(cropped_drone_img)
                    np_planet = np.array(cropped_planet_img)
                    MSE = metrics.mean_squared_error(np_drone.flatten(),
                                                     np_planet.flatten())
                    MSE_tt.append(MSE)
                    SSIM = compare_ssim(cropped_drone_img, cropped_planet_img)
                    SSIM_tt.append(SSIM)
            MSE_global_wl.append(MSE_tt)
            SSIM_global_wl.append(SSIM_tt)

    import pandas as pd
    x_2 = [i * i for i in x_1]
    df_r = pd.DataFrame(MSE_global_r,
                        index=[
                            "image 1", "image 2", "image 3", "image 4",
                            "image 5", "image 6", "image 7", "image 8",
                            "image 9", "image 10", "image 11", "image 12",
                            "image 13", "image 14", "image 15", "image 16",
                            "image 17", "image 18", "image 19", "image 20"
                        ],
                        columns=x_2)
    tmp_df_r = df_r

    df_wl = pd.DataFrame(MSE_global_wl,
                         index=[
                             "image 1", "image 2", "image 3", "image 4",
                             "image 5", "image 6", "image 7", "image 8",
                             "image 9", "image 10", "image 11", "image 12",
                             "image 13", "image 14", "image 15", "image 16",
                             "image 17", "image 18", "image 19", "image 20"
                         ],
                         columns=x_2)
    tmp_df_wl = df_wl

    A_r = []

    for k in tmp_df_r.keys():
        row_df = tmp_df_r[k]
        #row_df_wt = tmp_df_wt[k]
        row_df_wl = tmp_df_wl[k]
        for row in row_df.index:
            a = [row, float(row_df[row]), float(k), "rl"]
            #b = [row, float(row_df_wt[row]), float(k), "wt-rl"]
            c = [row, float(row_df_wl[row]), float(k), "wl"]
            A_r += [a]
            #A_r += [b]
            A_r += [c]

    new_pd_r = pd.DataFrame(
        A_r, columns=["Image", "Distance", "Area", "Experiment"])

    import matplotlib.pyplot as plt
    import seaborn as sns
    plt = sns.lineplot(x="Area",
                       y="Distance",
                       hue="Experiment",
                       data=new_pd_r,
                       palette=["g", "r"])
    plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    plt.set(xlabel="Area in $m^2$", ylabel='MSE')
コード例 #20
0
from PIL import Image
import math
import cv2

img_A = '立ち/イージス/基本.png'
img_B = '立ち/イージス/基本/笑顔.png'

# img_A = '016400_data_A.jpg'
# img_B = '016400_data_B.jpg'

img_A = Image.open(img_A)
img_B = Image.open(img_B)

# img_A = img_A.convert('RGB')
# img_B = img_B.convert('RGB')

# --------------------------------------
# img_A = np.array(img_A) / 127.5 - 1
# img_B = np.array(img_B) / 127.5 - 1
#
# sub = (img_A - img_B)
# mse = np.multiply(sub, sub).mean()
# psnr = 10 * math.log10(2**2 / mse)

ssim = compare_ssim(img_A, img_B)

# print("mse: ", mse)
# print("psnr: ", psnr)
print("ssim: ", ssim)

コード例 #21
0
fig.add_subplot(gs2[1])  # In amplitude
plt.title('Amplitude Convergence')
plt.plot(Iteration, rms_fourier)
plt.xlabel('Iteration Number')
plt.ylabel('RMS_amplitude(dB)')

plt.show()

# Comparison of two images using the structural similarity algorithm (SSIM).
# https://pypi.org/project/SSIM-PIL/

# Amplitude comparison using SSIM:
image_target = Image.fromarray((mat2level(Lt) * 255).astype(int), 'L')
image_recovered = Image.fromarray(
    (mat2level(np.abs(E_final)) * 255).astype(int), 'L')
value = compare_ssim(image_target, image_recovered)
print('\n', "The SSIM index value for amplitude calculation is Q = ",
      '{:f}'.format(value))

# Phase comparison using SSIM:
image_target = Image.fromarray((mat2level(Lp) * 255).astype(int), 'L')
image_recovered = Image.fromarray((mat2level(Lr) * 255).astype(int), 'L')
value = compare_ssim(image_target, image_recovered)
print('\n', "The SSIM index value for phase calculation is Q = ",
      '{:f}'.format(value), '\n')

# Save results in cvs files ##################################################################################################################
input = str(
    input(
        "Save values of the obtained phase-mask and the input field Ei?  Y/[N] = "
    ))
コード例 #22
0
        enhancer = enhancer_dict[image_name]
        image_dict = {}
        for param_type in param_type_list:
            image_dict[param_type] = enhancer.org_enhance(
                param_dict[param_type])
            image_dict[param_type].save(
                str(result_dir_path / (param_type + '.png')))

        param_error_dict = {
            'optimize-target': calc_error(optimized_param, target_param),
            'optimize-train': calc_error(optimized_param, best_train_param),
        }

        ssim_error_dict = {
            'optimize-target':
            compare_ssim(image_dict['optimize'], image_dict['target']),
            'optimize-train':
            compare_ssim(image_dict['optimize'], image_dict['train_dataset'])
        }
        write_data = {
            'param': param_dict,
            'error': {
                'param': param_error_dict,
                'ssim': ssim_error_dict
            }
        }

        with open(str(result_dir_path / 'data.json'), 'w') as fp:
            json.dump(write_data, fp, indent=4)
コード例 #23
0
def calc_ssim(rec_img, mod_img):
    return compare_ssim(rec_img, mod_img)
コード例 #24
0
img1 = Image.open(r"Unknown/test/5 new_faces.jpg")
img2 = Image.open(r"Unknown/test/20 new_faces.jpg")

hash0 = imagehash.average_hash(img1)
hash1 = imagehash.average_hash(img2)

# check width of the images are equal or not
if img1.width < img2.width:
    img2 = img2.resize((img1.width, img1.height))
else:
    img1 = img1.resize((img2.width, img2.height))

from SSIM_PIL import compare_ssim

value = compare_ssim(img1, img2)
print(value)

cutoff = 5

if hash0 - hash1 < cutoff:
    print('images are similar')
else:
    print('images are not similar')

# cascade classifier
# import cv2
# import face_recognition
#
# face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_fullbody.xml')
# upper_body = cv2.CascadeClassifier('haarcascades/haarcascade_upperbody.xml')
コード例 #25
0
ファイル: test_effect.py プロジェクト: thsshz/DeblurGAN
web_dir = os.path.join(opt.results_dir, opt.name, '%s_%s' % (opt.phase, opt.which_epoch))
webpage = html.HTML(web_dir, 'Experiment = %s, Phase = %s, Epoch = %s' % (opt.name, opt.phase, opt.which_epoch))
# test
avgPSNR = 0.0
avgSSIM = 0.0
counter = 0
print(len(dataset))
for i, data in enumerate(dataset):
    if i >= opt.how_many:
        break
    counter += 1
    model.set_input(data)
    model.test()
    visuals = model.get_current_visuals()
    avgPSNR += PSNR(visuals['fake_B'],visuals['real_B'])
    pilFake = Image.fromarray(visuals['fake_B'])
    pilReal = Image.fromarray(visuals['real_B'])
    avgSSIM += compare_ssim(pilFake, pilReal)
    img_path = model.get_image_paths()
    print('process image... %s' % img_path)
    visualizer.save_images(webpage, visuals, img_path)

print(counter)
avgPSNR /= counter
avgSSIM /= counter
print('PSNR = %f, SSIM = %f' % (avgPSNR, avgSSIM))
#f = open('effect.txt', 'a')
#f.write(str(counter) + ' ' + str(avgPSNR) + ' ' + str(avgSSIM))
#f.close()
webpage.save()
コード例 #26
0
ファイル: ssim.py プロジェクト: saisglu/image-comparison
def find_similarity(image1_path, image2_path):
    image1 = Image.open(image1_path)
    image2 = Image.open(image2_path)
    value = compare_ssim(image1, image2)
    return round((1 - value), 6)
コード例 #27
0
    x={"x": X[:,:,:,:]},
    y=Y[:,:,:,:],
    batch_size = 1,
    shuffle=False)
predict_results = AutoEncoder.predict(input_fn=predict_input_fn)

sum_mae_rad41 = 0
sum_mse_rad41 = 0
sum_ssim_rad41 = 0

for im_num in range(0, Y.shape[0]):
    prediction = next(predict_results)
    true_image = Y[im_num,:,:,:]
    sum_mae_rad41 += np.mean(np.abs(prediction - true_image))
    sum_mse_rad41 += np.mean(np.power((prediction - true_image), 2))
    sum_ssim_rad41 += compare_ssim(Image.fromarray((prediction[:,:,0] * 255).astype('uint8'), 'L'),
             Image.fromarray((true_image[:,:,0] * 255).astype('uint8'), 'L'))
    if(im_num % 1000 == 0):
        print("Current mae is " + str(sum_mae_rad41) + " and mse is " + str(sum_mse_rad41) + " and ssim is " + str(sum_ssim_rad41) + " at picture " + str(im_num))
        
sum_mae_rad41 /= X.shape[0]
sum_mse_rad41 /= X.shape[0]
sum_ssim_rad41 /= X.shape[0]

# Evaluate on rad_15
X = np.load('/scratch2/ttoebro/data/X_test_rad_15.npy')
Y = np.load('/scratch2/ttoebro/data/Y_test_rad_15.npy')

# Evaluate the model and print results
predict_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={"x": X[:,:,:,:]},
    y=Y[:,:,:,:],
コード例 #28
0
def ssim(path1, path2):
    img1 = Image.open(path1)
    img2 = Image.open(path2)
    return compare_ssim(img1, img2)
コード例 #29
0
def ssim_PIL(a, b):
    b = Image.open(b)
    return np.round(compare_ssim(a, b), 4)
コード例 #30
0
from skimage import data, img_as_float
from skimage.metrics import structural_similarity as ssim

from PIL import Image
from geoarray import GeoArray
from skimage.measure import compare_ssim as ssim

im1 = (Image.open("landsat1_10758.TIF"))
im2 = (Image.open("landsat2_10758.TIF"))

mask = np.ones((256, 256, 3))
#mask[64:192,64:192]=1
mask[96:160, 96:160, :] = 0
crop = im2.crop((96, 160, 96 + 64, 160 + 64))

crop.save("cropped_im2.TIF")
im_list = []

count = 0
for i in range(0, 256, 64):
    for j in range(0, 256, 64):
        count += 1

        tempIm = im1.crop((i, j, i + 64, j + 64))

        tempIm.save("im_" + str(count) + "_" + str(i) + str(j) + ".TIF")
        ssim = compare_ssim(tempIm, crop)
        im_list.append(ssim)
        print("for image", count, "ssim is ", ssim)
        #.bar(x, y[:, i], color=plt.cm.Paired(i / 10.))
print("max", min(im_list))