我试图创建一种算法来定位二进制图像的一列中的白色像素,然后将每个白色像素的y坐标/列数相加,然后将该值除以该列中白色像素的数目,在为了获得该列中的“平均/中间位置”白色像素。然后返回可以绘制的(x,y)坐标。对于图像中的每一列重复此过程,并且每次sy设置回0时。
最终目标不是像线条的numpy数组current line multiple thicks wide array所示,而是使用多像素宽/宽像素的线,而是保留了原来的形状,而只有一像素宽的线。我计划通过选择“每列中的平均定位白色像素”来做到这一点。然后,我将使用这些像素获得要绘制的x和y坐标。
这是我所拥有的
sx = x = img.shape[1]
sy = 0
whitec = cv2.countNonZero(img.shape[1])
arrayOfMeanY = [] #array to place (x,y) co-ordinate in
#Select column to iterate
for x in range(img.shape[1]):
# iterating through individual items in the column
for y in range(img.shape[0]):
# Checking for white pixels
pixel = img[x,y]
if pixel == 255:
# Then we check the y values of the white pixels in the column and add them all up
sy = sy+y
whitec +=1
# Doing the calculation for the mean and putting it into the meanY list
sy = sy/whitec
y = sy
print img[x,y]
array.append(y)
cv2.waitKey(0)
# reset sy to 0 for the next column
sy = 0
我的问题是我在运行代码时收到此错误:
File "<ipython-input-6-e4c2225ff632>", line 27, in <module>
whitec = cv2.countNonZero(img.shape[1]) #n= number of white pixels
in the column
TypeError: src is not a numpy array, neither a scalar
如何纠正此问题,一旦纠正此问题,我的编码就会执行我上面描述的操作。
最佳答案
这里不需要循环。使用numpy
,您几乎不需要遍历单个像素。
相反,创建一个函数,该函数获取每列非零像素的平均值(我将其转换为np.intp
以对图像进行索引;您可以仅使用int()
进行转换,但numt用于将Numy用于索引数组,因此,它有点更合适)。
def avgWhiteLocOverCol(col):
return np.intp(np.mean(np.where(col)))
然后,您可以使用
np.intp
简单地将函数应用于所有列。avgRows = np.apply_along_axis(avgWhiteLocOverCol, 0, img)
例如,让我们创建一个在中间行和对角线上带有白色像素的图像:
import numpy as np
import cv2
img = np.eye(500)*255
img[249,:] = 255
cv2.imshow('',img)
cv2.waitKey(0)
然后,我们可以在每列上应用该函数,这将给出斜率一半的线:
def avgWhiteLocOverCol(col):
return int(np.mean(np.where(col)))
avgRows = np.apply_along_axis(avgWhiteLocOverCol, 0, img)
avgIndImg = np.zeros_like(img)
avgIndImg[avgRows,range(img.shape[1])] = 255
cv2.imshow('',avgIndImg)
cv2.waitKey(0)
关于python-2.7 - 查找一列中 “mean positioned”白色像素并为每列重复该过程的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45338482/