如何比较python中的两个图像?

2024-10-02 12:37:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码是:

import cv2

from PIL import Image

import numpy as np

img=cv2.imread("IMG040.jpg")

img2=cv2.imread("IMG040.jpg")

p1 = np.array(img)

p2 = np.array(img2)

img3=img-img2

p3 = np.array(img3)

if p3==0 :
    print "the same"
else: 
    print"not the same"


but I have this problem
File "part2.py", line 10, in <module>
    if p3==0 :

错误消息:

^{pr2}$

Tags: theimportimgifnparraycv2jpg
2条回答

表达式

p3==0

创建布尔numpy数组。Pythonif语句不知道如何将整个数组解释为true或false。这就是错误消息的意思。您可能想知道是否所有元素都为零,这就是为什么错误消息建议您使用all()。在

最后,你会这样做的

^{pr2}$

但是,比较numpy数组和allclose方法更好,后者可以解释数值错误。所以试着换掉这个

img3=img-img2

p3 = np.array(img3)

if p3==0 :
    print "the same"
else: 
    print"not the same"

if np.allclose(img, img2):
    print "the same"
else:
    print "not the same"

你需要这样做if语句:

if np.all(p3==0):
    print 'The same'
else:
    print 'Not the same'

相关问题 更多 >

    热门问题