使用图像:imgcompare不支持列表?

2024-10-02 00:33:13 发布

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

import imgcompare

for filename in os.listdir(myPath):
     if filename.endswith(".png"):
         listIm1.append(filename)

for filename2 in os.listdir(myPath2):
     if filename2.endswith(".png"):
         listIm2.append(filename2)

所以我用图像填充我的两个列表,现在我想按照相同的索引逐个比较这两个列表的图像,例如:
listIm1[0]与listImg2[0]
listIm1[1]与listImg2[1]
等等。。。这就是代码:

for item in listIm1:
        ifSame = imgcompare.is_equal(listIm1[item],listIm2[item],tolerance=2)
        print ifSame

但是得到错误:

same = imgcompare.is_equal(listIm1[item], listIm2[item], tolerance=2)
TypeError: list indices must be integers, not str

it seems that imgcompare.is_equal() does not work with lists, is there some pythonic expedient to make it works?


Tags: inforifpngisosequalfilename
3条回答

这里的问题是您试图通过使用item获得listIm1的索引。您要做的是使用range(),例如:

for i in range(len(listIm1)):
            ifSame = imgcompare.is_equal(listIm1[i],listIm2[i],tolerance=2)

正如@Matt所指出的,只有当您事先知道列表的长度相同时,这才有效,否则它将抛出索引错误。你知道吗

 if filename2.endswith(".png"):
         listIm2.append(filename2)

for item in listIm1:
        # item = "someimagine.png"
 ifSame = imgcompare.is_equal(listIm1[item],listIm2[item],tolerance=2)
        #listIm1[someimagine.png] is what you are asking => retrun Type Error

我猜你在找这样的东西:

编辑:

import os

for filename in os.listdir(myPath):
    if filename2.endswith(".png"):
       img_path = os.path.join(myPath,filename2)  
       listIm2.append(img_path)

listIm1 = [] 
listIm2 = []
for i in range(len(listIm1)):

     ifSame = imgcompare.is_equal(listIm1[i],listIm2[i],tolerance=2)
     print ifSame

最好是len(listIm1)==len(listIm2)

使用for-each循环,它获取所提供列表listIm1中的每个元素并将其存储在临时变量item中,然后将item(这是一个字符串)作为两个列表的索引传递。列表的索引必须是整数,这就是您得到的错误。你知道吗

for dir1_file in listIm1:
    for dir2_file in listIm2:
        ifSame = imgcompare.is_equal(dir1_file,dir2_file,tolerance=2)
        print ifSame

此代码使用两个for-each循环,它查看两个列表中的每个元素,并将它们用作方法的参数。你知道吗

相关问题 更多 >

    热门问题