在python中使用and运算符时出错

2024-10-02 12:30:54 发布

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

我想使用for循环提取目录中的2张照片。在每次迭代中,它都会带来一张照片。获取两张照片后,将触发另一个if语句,并将打印“成功从目录中提取的两张图像”。这是代码==>

import cv2

import os

import re

from skimage.io import imread,imshow,imsave

images =os.listdir('D:\programs python/regeneration\Mi3_Aligned/1')

img = None

ref_img = None

for i in images:

    if i == "1.bmp":

        img = imread('D:\programs python/regeneration\Mi3_Aligned/1/' + i)

        img = cv2.resize(img, (980, 980), cv2.INTER_AREA)

    if i == "2.bmp":

        ref_img = imread('D:\programs python/regeneration\Mi3_Aligned/1/'+ i)

        ref_img = cv2.resize(img, (980, 980), cv2.INTER_AREA)

    if (img!=None and ref_img!=None):

        print("Both images extracted from directory successfully")

但它产生了一个错误,我无法理解问题是什么

if (img!=None and ref_img!=None):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

请帮忙


Tags: import目录nonerefimgforifcv2
3条回答

错误提示您,您正在尝试比较一个数组变量

docs for ^{}表示它返回一个数组

None相比,您可以利用Python中的空数组是错误的这一事实

if img and ref_img:
    print('Both images extracted from directory successfully')

问题源于数组和不同类型的变量/值之间的比较。我建议改用这个:

if img and ref_img:
    print("Both images extracted from directory successfully")

如果省略要比较的变量,python只会检查值是否为空/None

您可以通过更改

if (img!=None and ref_img!=None):

if img is not None and ref_img is not None:

数组有一个==!=的实现,它返回另一个数组而不是单个布尔值。但是... is not None将始终计算为真或假

相关问题 更多 >

    热门问题