计算并探究图像原图、旋转、添加噪声的相似度

很久没有更新了,今天接了一个简单的单子,做计算并探究图像原图、旋转、添加噪声的相似度。代码如下:

上次发的一个文章许多大型的网站转发没有备注文章出处,并且没有经过我的同意,如果再有下次直接投诉。(脚本之家,易采站长站、编程客栈等网站)

# -*- coding: utf-8 -*-
# !/usr/bin/env python
# @Time    : 2021/10/1 14:52
# @Author  : PanBo
# @Desc    : 余弦相似度计算
# @Software: PyCharm
from PIL import Image
from numpy import average, dot, linalg
import cv2 as cv
import numpy as np



def get_thum(image, size=(64, 64), greyscale=False):

    image = image.resize(size, Image.ANTIALIAS)
    if greyscale:
        image = image.convert('L')
    return image

def image_similarity_vectors_via_numpy(image1, image2):
    image1 = get_thum(image1)
    image2 = get_thum(image2)
    images = [image1, image2]
    vectors = []
    norms = []
    for image in images:
        vector = []
        for pixel_tuple in image.getdata():
            vector.append(average(pixel_tuple))
        vectors.append(vector)
        norms.append(linalg.norm(vector, 2))
    a, b = vectors
    a_norm, b_norm = norms
    res = dot(a / a_norm, b / b_norm)
    return res

def random_noise(image, noise_num):
    img = cv.imread(image)
    img_noise = img
    rows, cols, chn = img_noise.shape
    for i in range(noise_num):
        x = np.random.randint(0, rows)
        y = np.random.randint(0, cols)
        img_noise[x, y, :] = 255
    return img_noise


origin_image = Image.open('1.png')
test_image = Image.open('2.jpg')
print("_____________________________原始图片相似度_____________________________________")
cosin = image_similarity_vectors_via_numpy(origin_image, test_image)
print('图片余弦相似度', cosin)

print("_____________________________图片旋转45度相似度_____________________________________")
rotate45_img = origin_image.rotate(45)
# rotate45_img.show()
cosin2 = image_similarity_vectors_via_numpy(rotate45_img, test_image)
print('图片旋转45度余弦相似度', cosin2)

print("_____________________________图片旋转90度相似度_____________________________________")
rotate90_img = origin_image.rotate(90)
# rotate90_img.show()
cosin3 = image_similarity_vectors_via_numpy(rotate90_img, test_image)
print('图片旋转90度余弦相似度', cosin3)

print("_____________________________图片旋转120度相似度_____________________________________")
rotate120_img = origin_image.rotate(120)
# rotate120_img.show()
cosin4 = image_similarity_vectors_via_numpy(rotate120_img, test_image)
print('图片旋转120度余弦相似度', cosin4)

print("_____________________________噪声图片相似度_____________________________________")
img_noise = random_noise("1.png", 3000)
cv.imshow("random_noise", img_noise)

# noise_image = Image.open("noise_img.png")
image = Image.fromarray(cv.cvtColor(img_noise, cv.COLOR_BGR2RGB))
cosin5 = image_similarity_vectors_via_numpy(image, test_image)
print('图片余弦相似度', cosin5)
cv.waitKey(0)

计算并探究图像原图、旋转、添加噪声的相似度

 

上一篇:搭建springboot+zookeeper+dubbo


下一篇:衰减器对系统Noise Figure的影响