问题描述
我想计算图像每一行中的像素变化(这意味着从黑色到白色或从白色到黑色的任何变化), 就像下面的图片: Example of letter A
change = [0 for k in range(test.shape[0])]
total = []
for x in range(test.shape[0]-1):
change[x]=0
for y in range(test.shape[1]-1):
if test[x,y+1] != test[x,y]:
change[x] = change[x] + 1
elif test[x+1,y+1] != test[x+1,y]:
change[x] = change[x] + 1
total.append(change[x])
解决方法
要计算一行的变化,只需将每个像素与同一行的下一个像素进行比较。
在您的代码中,只需删除elif
。
change = [0 for k in range(test.shape[0])] # changes per row
total = []
for x in range(test.shape[0]): # each row
change[x]=0 # not needed
for y in range(test.shape[1]-1): # each column
if test[x,y+1] != test[x,y]:
change[x] = change[x] + 1
# elif test[x+1,y+1] != test[x+1,y]: # not needed
# change[x] = change[x] + 1 # not needed
total.append(change[x])
,
您可以尝试使用Numpy:
out=np.sum(np.absolute(np.diff(np.double(img),axis=1))/255.0,axis=1)