当前位置: 首页>>代码示例>>Python>>正文


Python measure.compare_ssim方法代码示例

本文整理汇总了Python中skimage.measure.compare_ssim方法的典型用法代码示例。如果您正苦于以下问题:Python measure.compare_ssim方法的具体用法?Python measure.compare_ssim怎么用?Python measure.compare_ssim使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在skimage.measure的用法示例。


在下文中一共展示了measure.compare_ssim方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: compare

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import compare_ssim [as 别名]
def compare(inp_img, out_img, calc_ssim=True, calc_msssim=True, calc_psnr=True):
    inp_img = _read_if_not_array(inp_img)
    out_img = _read_if_not_array(out_img)

    assert inp_img.shape == out_img.shape

    def get_ssim():
        return compare_ssim(inp_img, out_img, multichannel=True, gaussian_weights=True, sigma=1.5)

    def get_msssim():
        return MultiScaleSSIM(make_batched(inp_img), make_batched(out_img))

    def get_psnr():
        return compare_psnr(inp_img, out_img)

    def _run_if(cond, fn):
        return fn() if cond else None

    return _run_if(calc_ssim, get_ssim), _run_if(calc_msssim, get_msssim), _run_if(calc_psnr, get_psnr) 
开发者ID:fab-jul,项目名称:imgcomp-cvpr,代码行数:21,代码来源:compare_imgs.py

示例2: slice_process

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import compare_ssim [as 别名]
def slice_process(x1, x2, y):
    if len(x1.shape) == 3: x1 = x1[0,:,:]
    if len(x2.shape) == 3: x2 = x2[0,:,:]
    if len(y.shape) == 3: y = y[0,:,:]

    # a scaled and shifted version of pred and bilinear
    x1 = 2*x1 + 100
    x2 = 2*x2 + 100

    # normalize/scale images
    (y_norm1, x1_norm) = norm_minmse(y, x1)
    (y_norm2, x2_norm) = norm_minmse(y, x2)

    # calulate psnr and ssim of the normalized/scaled images
    psnr1 = compare_psnr(*(y_norm1, x1_norm), data_range = 1.)
    psnr2 = compare_psnr(*(y_norm2, x2_norm), data_range = 1.)
    ssim1 = compare_ssim(*(y_norm1, x1_norm), data_range = 1.)
    ssim2 = compare_ssim(*(y_norm2, x2_norm), data_range = 1.)
    return psnr1, ssim1, psnr2, ssim2, y_norm1, x1_norm, y_norm2, x2_norm 
开发者ID:BPHO-Salk,项目名称:PSSR,代码行数:21,代码来源:metric_gen.py

示例3: _test_single

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import compare_ssim [as 别名]
def _test_single(dshape):
    d0 =np.zeros(dshape,np.float32)

    ss = tuple(slice(s//4,-s//4) for s in dshape)
    d0[ss] = 10.

    d1 = d0+np.random.uniform(0, 1, dshape).astype(np.float32)

    drange = np.amax(d0) - np.amin(d0)
    print(drange)

    m1, m2 = compare_ssim(d0,d1, data_range = drange), ssim(d0,d1)

    print("shape: %s \t\tSSIM = %.2f\t\tdifference: %s" % (dshape, m1, np.abs(m1-m2)))
    npt.assert_almost_equal(m1,m2, decimal = 5)
    return m1, m2 
开发者ID:maweigert,项目名称:gputools,代码行数:18,代码来源:test_ssim.py

示例4: avg_SSIM

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import compare_ssim [as 别名]
def avg_SSIM(self):

        ori_r_channel = np.transpose(np.round(self.nature_samples * 255), (0, 2, 3, 1)).astype(dtype=np.float32)
        adv_r_channel = np.transpose(np.round(self.adv_samples * 255), (0, 2, 3, 1)).astype(dtype=np.float32)

        totalSSIM = 0
        cnt = 0

        """
        For SSIM function in skimage: http://scikit-image.org/docs/dev/api/skimage.measure.html

        multichannel : bool, optional If True, treat the last dimension of the array as channels. Similarity calculations are done 
        independently for each channel then averaged.
        """
        for i in range(len(self.adv_samples)):
            if self.successful(adv_softmax_preds=self.softmax_prediction[i], nature_true_preds=self.labels_samples[i],
                               targeted_preds=self.targets_samples[i], target_flag=self.Targeted):
                cnt += 1
                totalSSIM += SSIM(X=ori_r_channel[i], Y=adv_r_channel[i], multichannel=True)

        print('ASS:\t{:.3f}'.format(totalSSIM / cnt))
        return totalSSIM / cnt

    # 6: PSD: Perturbation Sensitivity Distance 
开发者ID:kleincup,项目名称:DEEPSEC,代码行数:26,代码来源:AttackEvaluations.py

示例5: generate

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import compare_ssim [as 别名]
def generate(self, x_fixed, x_target_fixed, pose_target_fixed, root_path=None, path=None, idx=None, save=True):
        G = self.sess.run(self.G, {self.x: x_fixed, self.pose_target: pose_target_fixed})
        ssim_G_x_list = []
        # x_0_255 = utils_wgan.unprocess_image(x_target_fixed, 127.5, 127.5)
        for i in xrange(G.shape[0]):
            # G_gray = rgb2gray((G[i,:]/127.5-1).clip(min=-1,max=1))
            # x_target_gray = rgb2gray((x_target_fixed[i,:]).clip(min=-1,max=1))
            G_gray = rgb2gray((G[i,:]).clip(min=0,max=255).astype(np.uint8))
            x_target_gray = rgb2gray(((x_target_fixed[i,:]+1)*127.5).clip(min=0,max=255).astype(np.uint8))
            ssim_G_x_list.append(ssim(G_gray, x_target_gray, data_range=x_target_gray.max() - x_target_gray.min(), multichannel=False))
        ssim_G_x_mean = np.mean(ssim_G_x_list)
        if path is None and save:
            path = os.path.join(root_path, '{}_G_ssim{}.png'.format(idx,ssim_G_x_mean))
            save_image(G, path)
            print("[*] Samples saved: {}".format(path))
        return G 
开发者ID:charliememory,项目名称:Pose-Guided-Person-Image-Generation,代码行数:18,代码来源:trainer.py

示例6: generate

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import compare_ssim [as 别名]
def generate(self, x_fixed, x_target_fixed, pose_fixed, part_bbox_fixed, root_path=None, path=None, idx=None, save=True):
        G_pose_rcv, G_pose = self.sess.run([self.G_pose_rcv, self.G_pose])
        G_pose_inflated = py_poseInflate(G_pose_rcv, is_normalized=True, radius=4, img_H=256, img_W=256)
        # G = self.sess.run(self.G, {self.x: x_fixed, self.G_pose_inflated: G_pose_inflated, self.part_bbox: part_bbox_fixed})
        G_pose_inflated_img = np.tile(np.amax((G_pose_inflated+1)*127.5, axis=-1, keepdims=True), [1,1,1,3])
        
        # ssim_G_x_list = []
        # for i in xrange(G_pose.shape[0]):
        #     G_gray = rgb2gray((G[i,:]).clip(min=0,max=255).astype(np.uint8))
        #     x_gray = rgb2gray(((x_fixed[i,:]+1)*127.5).clip(min=0,max=255).astype(np.uint8))
        #     ssim_G_x_list.append(ssim(G_gray, x_gray, data_range=x_gray.max() - x_gray.min(), multichannel=False))
        # ssim_G_x_mean = np.mean(ssim_G_x_list)
        if path is None and save:
            # path = os.path.join(root_path, '{}_G_ssim{}.png'.format(idx,ssim_G_x_mean))
            # save_image(G, path)
            # print("[*] Samples saved: {}".format(path))
            path = os.path.join(root_path, '{}_G_pose.png'.format(idx))
            save_image(G_pose, path)
            print("[*] Samples saved: {}".format(path))
            path = os.path.join(root_path, '{}_G_pose_inflated.png'.format(idx))
            save_image(G_pose_inflated_img, path)
            print("[*] Samples saved: {}".format(path))
        return G_pose 
开发者ID:charliememory,项目名称:Disentangled-Person-Image-Generation,代码行数:25,代码来源:trainer.py

示例7: compute_psnr_and_ssim

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import compare_ssim [as 别名]
def compute_psnr_and_ssim(image1, image2, border_size=0):
    """
    Computes PSNR and SSIM index from 2 images.
    We round it and clip to 0 - 255. Then shave 'scale' pixels from each border.
    """
    if len(image1.shape) == 2:
        image1 = image1.reshape(image1.shape[0], image1.shape[1], 1)
    if len(image2.shape) == 2:
        image2 = image2.reshape(image2.shape[0], image2.shape[1], 1)

    if image1.shape[0] != image2.shape[0] or image1.shape[1] != image2.shape[1] or image1.shape[2] != image2.shape[2]:
        return None

    image1 = trim_image_as_file(image1)
    image2 = trim_image_as_file(image2)

    if border_size > 0:
        image1 = image1[border_size:-border_size, border_size:-border_size, :]
        image2 = image2[border_size:-border_size, border_size:-border_size, :]

    psnr = compare_psnr(image1, image2, data_range=255)
    ssim = compare_ssim(image1, image2, win_size=11, gaussian_weights=True, multichannel=True, K1=0.01, K2=0.03,
                        sigma=1.5, data_range=255)
    return psnr, ssim 
开发者ID:jiny2001,项目名称:dcscn-super-resolution,代码行数:26,代码来源:utilty.py

示例8: compare_images

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import compare_ssim [as 别名]
def compare_images(image_a, image_b, title):
    # compute the mean squared error and structural similarity
    # index for the images
    m = mse(image_a, image_b)
    s = compare_ssim(image_a, image_b, multichannel=True)

    # setup the figure
    fig = plt.figure(title)
    plt.suptitle("MSE: %.2f, SSIM: %.2f" % (m, s))

    # show first image
    ax = fig.add_subplot(1, 2, 1)
    plt.imshow(image_a, cmap=plt.cm.gray)
    plt.axis("off")

    # show the second image
    ax = fig.add_subplot(1, 2, 2)
    plt.imshow(image_b, cmap=plt.cm.gray)
    plt.axis("off")

    # show the images
    plt.show() 
开发者ID:will7200,项目名称:Yugioh-bot,代码行数:24,代码来源:test_nox.py

示例9: group_semantic_frames

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import compare_ssim [as 别名]
def group_semantic_frames(frames, threshold=None):
    '''
    Given an array of frames extracted from a video, break these into subarrays of semantically similiar frames.
    For now use the Structural Similarity Index and once it reaches a certain threshold break off. Return an array of
    these sub arrays.
    '''
    frame_clusters = []
    group = []
    print("Grouping semantic frames")
    for frame in tqdm(frames):
        if len(group) == 0:
            group.append(frame)
        else:
            # compute structural similarity index between current image and oldest image in the frame group
            s = 0.0
            if torch.cuda.is_available():
                threshold = .28
                img1 = torch.from_numpy(np.rollaxis(group[0], 2)).float().unsqueeze(0)/255.0
                img2 = torch.from_numpy(np.rollaxis(frame, 2)).float().unsqueeze(0)/255.0
                img1 = img1.cuda()
                img2 = img2.cuda()
                img1 = Variable( img1,  requires_grad=False)
                img2 = Variable( img2, requires_grad = True)
                s = pytorch_ssim.ssim(img1, img2)
                s = s.cpu().data.numpy()
            else:
                threshold = 0.35
                s = ssim(group[0], frame, multichannel=True)
            if s < threshold:
                frame_clusters.append(list(group))
                group.clear()
            # TODO: If we don't append the frame each time we only get the salient images which reduces number of frames
            group.append(frame)
    
    if len(group) > 0:
        frame_clusters.append(list(group))
    return frame_clusters 
开发者ID:AkshatSh,项目名称:VideoSearchEngine,代码行数:39,代码来源:video_utils.py

示例10: execute

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import compare_ssim [as 别名]
def execute(
        self, template_object: np.ndarray, target_object: np.ndarray, *_, **__
    ) -> FindItEngineResponse:
        resp = FindItEngineResponse()

        resized_target = cv2.resize(
            target_object, template_object.shape[::-1], interpolation=cv2.INTER_CUBIC
        )
        ssim = compare_ssim(resized_target, template_object)

        resp.append("conf", self.__dict__)
        resp.append("ssim", ssim, important=True)
        resp.append("ok", True, important=True)
        return resp 
开发者ID:williamfzc,项目名称:findit,代码行数:16,代码来源:sim.py

示例11: ssim_score

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import compare_ssim [as 别名]
def ssim_score(generated_images, reference_images):
    ssim_score_list = []
    for reference_image, generated_image in zip(reference_images, generated_images):
        ssim = compare_ssim(reference_image, generated_image, gaussian_weights=True, sigma=1.5,
                            use_sample_covariance=False, multichannel=True,
                            data_range=generated_image.max() - generated_image.min())
        ssim_score_list.append(ssim)
    return np.mean(ssim_score_list) 
开发者ID:budui,项目名称:Human-Pose-Transfer,代码行数:10,代码来源:getMetrics_market.py

示例12: compute_SSIM

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import compare_ssim [as 别名]
def compute_SSIM(out_img, ground_truth):
    img = out_img.copy().transpose(1, 2, 0)
    img[img > 1.] = 1.
    img[img < 0.] = 0.
    gt = ground_truth.copy().transpose(1, 2, 0)
    gt[gt > 1.] = 1.
    gt[gt < 0.] = 0.
    return compare_ssim(img, gt, gaussian_weights=True, sigma=1.5, use_sample_covariance=False, multichannel=True,
                        data_range=1.) 
开发者ID:shirakawas,项目名称:ASNG-NAS,代码行数:11,代码来源:utils.py

示例13: compute_image_quality_metrics

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import compare_ssim [as 别名]
def compute_image_quality_metrics(ground_truth_images, ground_truth_angles, generated_images, generated_angles):
    # order the images according to ascending angle
    ground_truth_images = ground_truth_images[np.argsort(ground_truth_angles[:, 0], 0)]
    generated_images = generated_images[np.argsort(generated_angles[:, 0], 0)]

    loop_mse, loop_nrmse, loop_ssim = [], [], []
    for (im_gt, im_gen) in zip(ground_truth_images, generated_images):
        loop_mse.append(mse(im_gt, im_gen))
        loop_nrmse.append(nrmse(im_gt, im_gen))
        loop_ssim.append(ssim(im_gt.squeeze(), im_gen.squeeze()))
    return np.array(loop_mse).mean(), np.array(loop_nrmse).mean(), np.array(loop_ssim).mean() 
开发者ID:Gordonjo,项目名称:versa,代码行数:13,代码来源:evaluate_view_reconstruction.py

示例14: calculate_ssim

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import compare_ssim [as 别名]
def calculate_ssim(output_img, target_img):
    target_tf = torch2numpy(target_img)
    output_tf = torch2numpy(output_img)
    ssim = 0.0
    n = 0.0
    for im_idx in range(output_tf.shape[0]):
        ssim += compare_ssim(target_tf[im_idx, ...],
                                             output_tf[im_idx, ...],
                                             multichannel=True,
                                             data_range=255)
        n += 1.0
    return ssim / n 
开发者ID:z-bingo,项目名称:FastDVDNet,代码行数:14,代码来源:data_utils.py

示例15: ssim

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import compare_ssim [as 别名]
def ssim(img, ref, dynamic_range=None):
    """ Compute SSIM. If inputs are 3D, average over axis=0.
        If dynamic_range != None, the same given dynamic range will be used for all slices in the volume. """
    assert img.ndim == ref.ndim
    assert img.ndim in [2, 3]
    if img.ndim == 2:
        img = img[np.newaxis]
        ref = ref[np.newaxis]

    # ssim averaged over slices
    ssim_slices = []
    ref_abs = np.abs(ref)
    img_abs = np.abs(img)

    for i in range(ref_abs.shape[0]):
        if dynamic_range == None:
            drange = np.max(ref_abs[i]) - np.min(ref_abs[i])
        else:
            drange = dynamic_range
        _, ssim_i = compare_ssim(img_abs[i], ref_abs[i],
                                 data_range=drange,
                                 gaussian_weights=True,
                                 use_sample_covariance=False,
                                 full=True)
        ssim_slices.append(np.mean(ssim_i))

    return np.mean(ssim_slices) 
开发者ID:VLOGroup,项目名称:mri-variationalnetwork,代码行数:29,代码来源:mriutils.py


注:本文中的skimage.measure.compare_ssim方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。