【python示例】读取图片中的非0像素点的坐标np.argwhere函数
【创作不易,求关注+点赞+收藏】😀
np.argwhere 是 NumPy 库中的一个函数,它用于返回输入数组中非零元素的索引。
non_zero_indices = np.argwhere(pixels != 0)
这行代码的作用是:
pixels != 0: 这是一个布尔表达式,用于检查 pixels 数组中的每个元素是否不等于0。这将返回一个与 pixels 形状相同的布尔数组,其中的元素是 True 或 False。
np.argwhere(…): 这个函数将上述布尔数组作为输入,并返回一个新的数组,其中只包含原始数组中非零元素的索引。
例如,如果 pixels 数组如下:
array([[ 1, 0, 0],
[ 0, 2, 0],
[ 0, 0, 3]])
执行 np.argwhere(pixels != 0) 将返回:
array([[0, 0],
[1, 1],
[2, 2]])
这表示 pixels 数组中有三个非零元素,它们分别位于第1行第1列、第2行第2列和第3行第3列的位置。
接下来我们进行示例分享,我们创建一个随机的图像,部分像素点数值是0,部分是非0,我们要通过上述的函数来读取非0的像素点的坐标。首先,我们的图像大小是300*300,像素大小是0.1mm,坐标的单位是mm。先通过np.argwhere函数读取非0像素点的索引位置,再通过建立坐标系来读取坐标点。
import numpy as np
# 这里我们创建一个示例图像,用随机数来模拟非零像素点
image = np.random.randint(0, 2, (300, 300))
# 图像尺寸
N = image.shape[0]
# 将图像转换为NumPy数组
pixels = np.array(image)
# 找到所有非零像素的索引
non_zero_indices = np.argwhere(pixels != 0)
# 假设每个像素的大小是0.1mm
pixel_size_mm = 0.1
center_x_mm = N * pixel_size_mm / 2
center_y_mm = N * pixel_size_mm / 2
# 存储坐标的列表
coordinates_mm = []
# 转换坐标并将它们添加到列表中
for idx in non_zero_indices:
x_mm = idx[1] * pixel_size_mm - center_x_mm
y_mm = idx[0] * pixel_size_mm - center_y_mm
coordinates_mm.append((x_mm, y_mm))
# 打印结果和坐标列表
for idx, coord in zip(non_zero_indices, coordinates_mm):
print(f"Pixel index: {idx}, Coordinate in mm: {coord}")
# 将坐标保存到文本文件
with open('coordinates.txt', 'w') as file:
for coord in coordinates_mm:
# 每个坐标占一行,格式为 "x,y"
file.write(f"{coord[0]},{coord[1]}\n")
# 打印整个坐标列表
print("\nAll coordinates in mm:")
for coord in coordinates_mm:
print(f"{coord[0]:.2f}, {coord[1]:.2f}")