不能在 2 个图像之间做余弦相似度,如何使两个图像具有相同的长度
can't do cosine similarity between 2 images, how to make both have the same length
我在做一些人脸验证的事情(我是新手)首先我矢量化了我想要比较的 2 张图片
filename1 = '/1_52381.jpg'
filename2 = '/1_443339.jpg'
img1 = plt.imread(filename1)
rows,cols,colors = img1.shape
img1_size = rows*cols*colors
img1_1D_vector = img1.reshape(img1_size).reshape(-1, 1)
img2 = plt.imread(filename2)
rows,cols,colors = img2.shape
img2_size = rows*cols*colors
img2_1D_vector = img2.reshape(img2_size).reshape(-1, 1)
(img2_1D_vector.shape,img1_1D_vector.shape)
在这里我得到了两个向量的暗淡:((30960, 1), (55932, 1)).
我的问题是如何使它们的长度相同,是否需要先将图片重塑为相同的大小?或者我可以在矢量化之后做?感谢阅读
是的,要计算余弦相似度,您需要向量具有相同的维度,并且在将其中一张图片重塑为向量之前调整其大小是一个很好的解决方案。
要调整大小,您可以使用 python 中可用的图像处理框架之一。
注意:它们是不同的algorithm/parameters,可用于调整大小。
# with skimage (you can also use PIL or cv2)
from skimage.transform import resize
shape = img1.shape
img2_resized = resize(img1, shape)
img1_vector = img1.ravel()
img2_vector = img2_resized.ravel()
# now you can perform your cosine similarity between img1_vector and img2_vector
# which are of the same dimension
您可能不想缩小大图,而是放大小图,因为放大可能会引入更多伪像。
您可能还希望在整个数据集中使用固定大小。
我在做一些人脸验证的事情(我是新手)首先我矢量化了我想要比较的 2 张图片
filename1 = '/1_52381.jpg'
filename2 = '/1_443339.jpg'
img1 = plt.imread(filename1)
rows,cols,colors = img1.shape
img1_size = rows*cols*colors
img1_1D_vector = img1.reshape(img1_size).reshape(-1, 1)
img2 = plt.imread(filename2)
rows,cols,colors = img2.shape
img2_size = rows*cols*colors
img2_1D_vector = img2.reshape(img2_size).reshape(-1, 1)
(img2_1D_vector.shape,img1_1D_vector.shape)
在这里我得到了两个向量的暗淡:((30960, 1), (55932, 1)).
我的问题是如何使它们的长度相同,是否需要先将图片重塑为相同的大小?或者我可以在矢量化之后做?感谢阅读
是的,要计算余弦相似度,您需要向量具有相同的维度,并且在将其中一张图片重塑为向量之前调整其大小是一个很好的解决方案。
要调整大小,您可以使用 python 中可用的图像处理框架之一。
注意:它们是不同的algorithm/parameters,可用于调整大小。
# with skimage (you can also use PIL or cv2)
from skimage.transform import resize
shape = img1.shape
img2_resized = resize(img1, shape)
img1_vector = img1.ravel()
img2_vector = img2_resized.ravel()
# now you can perform your cosine similarity between img1_vector and img2_vector
# which are of the same dimension
您可能不想缩小大图,而是放大小图,因为放大可能会引入更多伪像。 您可能还希望在整个数据集中使用固定大小。