在 Python 中将仅黑色或白色的 rgb 数组转换为 1 或 0 数组
Convert a black or white only rgb array into a 1 or 0 array in Python
我对 python 比较陌生,我正在处理一张包含 'hits' 的图像,该图像来自完全黑白的粒子探测器。
为了计算命中次数(并稍后将命中与不同的粒子分开),我需要对相邻的白色像素进行分组。
我的代码目前确保图像只有黑色或白色,然后尝试使用 scipy 标签函数对白色像素进行分组(这应该有效,因为它将任何 none 0 值和我让所有黑色像素都为 0,所有白色像素都为 1。但是它 returns 0 标签,我不确定为什么。我认为这可能与它不仅是 1 和 0,而且仍然是元组的事实有关我正在使用的列表。
有没有一种方法可以根据像素是黑色还是白色来创建简单的 1 或 0 数组?
def analyseImage(self, imPath):
img = Image.open(imPath)
grey = img.convert('L')
bw = np.asarray(grey).copy()
#Switches black and white for label to be effective
bw[bw < 128] = 255 # White
bw[bw >= 128] = 0 # Black
lbl, nlbls = label(bw)
labels = range(1, nlbls + 1)
coords = [np.column_stack(np.where(lbl == k)) for k in labels]
imfile = Image.fromarray(bw)
在 bw[bw < 128] = 255 # White
行之后,所有 < 128 的元素都被设置为 255,这意味着现在每个元素都 >= 128(因为 255 是 > 128)。然后,下一行将每个元素替换为 0,因为所有元素现在都 >= 128.
试试看:
def analyseImage(self, imPath):
img = Image.open(imPath)
grey = img.convert('L')
#Switches black (0) and white (255) for label to be effective
bw = np.asarray([255 if x < 128 else 0 for x in grey])
lbl, nlbls = label(bw)
labels = range(1, nlbls + 1)
coords = [np.column_stack(np.where(lbl == k)) for k in labels]
imfile = Image.fromarray(bw)
或者,您可以创建 bw
的副本,并在与 128 的比较中使用该副本:
bw2 = bw.copy()
bw[bw2 < 128] = 255
bw[bw2 >= 128] = 0
我对 python 比较陌生,我正在处理一张包含 'hits' 的图像,该图像来自完全黑白的粒子探测器。
为了计算命中次数(并稍后将命中与不同的粒子分开),我需要对相邻的白色像素进行分组。
我的代码目前确保图像只有黑色或白色,然后尝试使用 scipy 标签函数对白色像素进行分组(这应该有效,因为它将任何 none 0 值和我让所有黑色像素都为 0,所有白色像素都为 1。但是它 returns 0 标签,我不确定为什么。我认为这可能与它不仅是 1 和 0,而且仍然是元组的事实有关我正在使用的列表。
有没有一种方法可以根据像素是黑色还是白色来创建简单的 1 或 0 数组?
def analyseImage(self, imPath):
img = Image.open(imPath)
grey = img.convert('L')
bw = np.asarray(grey).copy()
#Switches black and white for label to be effective
bw[bw < 128] = 255 # White
bw[bw >= 128] = 0 # Black
lbl, nlbls = label(bw)
labels = range(1, nlbls + 1)
coords = [np.column_stack(np.where(lbl == k)) for k in labels]
imfile = Image.fromarray(bw)
在 bw[bw < 128] = 255 # White
行之后,所有 < 128 的元素都被设置为 255,这意味着现在每个元素都 >= 128(因为 255 是 > 128)。然后,下一行将每个元素替换为 0,因为所有元素现在都 >= 128.
试试看:
def analyseImage(self, imPath):
img = Image.open(imPath)
grey = img.convert('L')
#Switches black (0) and white (255) for label to be effective
bw = np.asarray([255 if x < 128 else 0 for x in grey])
lbl, nlbls = label(bw)
labels = range(1, nlbls + 1)
coords = [np.column_stack(np.where(lbl == k)) for k in labels]
imfile = Image.fromarray(bw)
或者,您可以创建 bw
的副本,并在与 128 的比较中使用该副本:
bw2 = bw.copy()
bw[bw2 < 128] = 255
bw[bw2 >= 128] = 0