我打开图像并将其转换为RGBA值数组。这是我的代码:
img = Image.open('17112013.png')
imgarray = array(img)
l = imgarray[:,1,1]
m = imgarray[1,:,1]
n = imgarray[1,1,:]
blueCount = 0
redCount = 0
flag = 0
for i in range(0,len(l)):
for j in range(0,len(m)):
if (imgarray[i,j] == [255,255,255,255]):
pass
if (imgarray[i,j] == [0,0,0,255] and flag == 0):
pass
if (imgarray[i,j] == [255,0,0,255] and flag == 0):
pass
if (imgarray[i,j] == [0,0,255,255]):
flag = 1
blueCount = blueCount + 1
if (imgarray[i,j] == [255,0,0,255] and flag == 1):
redCount = redCount + 1
if (imgarray[i,j] == [0,0,0,255] and flag == 1):
flag = 0
if (imgarray[i,j] == [255,255,255,255] and flag == 1):
flag = 0
如果我这样运行,我收到以下内容:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我知道我需要将这些用于'如果'包含numpy数组的语句;但是,我不确定实现它的正确语法。可能只是愚蠢,但任何帮助都会受到赞赏。
答案 0 :(得分:0)
您可能需要以下内容:
if np.all(imgarray[i,j] == [255,255,255,255]):
如果imgarray
的特定切片确实是[255,255,255,255]
,则相等比较将返回array([ True, True, True, True], dtype=bool)
。正如您所发现的那样,您不能指望if
直接知道如何处理此布尔数组,但如果数组{中的所有值,则函数numpy.all(x)
将返回True
{1}}等同于x
和True
。
答案 1 :(得分:0)
正如错误所说,当使用带有逻辑值数组的if
时,不清楚你想要什么。我假设如果当前imgarray[i,j]
的每个部分都等于比较数组,那么你只想要真。您最好使用过多的括号和逻辑&
运算符来明确您想要的内容。运行,
import Image
import numpy as np
img = Image.open('17112013.png')
imgarray = np.array(img)
l = imgarray[:,1,1]
m = imgarray[1,:,1]
n = imgarray[1,1,:]
blueCount = 0
redCount = 0
flag = 0
for i in range(0,len(l)):
for j in range(0,len(m)):
if (np.all(imgarray[i,j] == [255,255,255,255])):
pass
if (np.all(imgarray[i,j] == [0,0,0,255]) & flag == 0):
pass
if (np.all(imgarray[i,j] == [255,0,0,255]) & flag == 0):
pass
if (np.all(imgarray[i,j] == [0,0,255,255])):
flag = 1
blueCount = blueCount + 1
if (np.all(imgarray[i,j] == [255,0,0,255]) & flag == 1):
redCount = redCount + 1
if (np.all(imgarray[i,j] == [0,0,0,255]) & flag == 1):
flag = 0
if (np.all(imgarray[i,j] == [255,255,255,255]) & flag == 1):
flag = 0
不确定你是否需要它?