同心环 raspberry pi

concentric rings raspberry pi

我希望创建一个简单的代码,使我能够分析使用 raspberry pi 相机拍摄的图像。

我想用python或raspbarian将图像分割成同心rings/annulus环,然后分析每个环中黑色像素的数量。

任何建议都会很棒!

我对 Rapberry Pi 了解不多,但我假设您可以将其相机中的图像作为普通图像文件访问,并且我假设您可以安装 PIL。

如果是这样,您可以打开图像,遍历其像素,并根据每个像素与中心的距离将其分类到一个波段中。

from PIL import Image
from collections import Counter
import math

RING_RADIUS = 15

img = Image.open("image.png")

center_x = img.size[0] / 2
center_y = img.size[1] / 2

results = Counter()
pix = img.load()
for i in range(img.size[0]):
    for j in range(img.size[1]):
        d = math.hypot(center_x - i, center_y - j)
        band = int(d / RING_RADIUS)
        if pix[i,j] == (0,0,0):
            results[band] += 1

for k,v in sorted(results.items()):
    print(f"Number of black pixels in ring #{k}: {v}")

让我们尝试 运行 这个示例图片:

结果:

Number of black pixels in ring #0: 145
Number of black pixels in ring #1: 150
Number of black pixels in ring #2: 150
Number of black pixels in ring #3: 150
Number of black pixels in ring #4: 453
Number of black pixels in ring #5: 337
Number of black pixels in ring #6: 613
Number of black pixels in ring #7: 489
Number of black pixels in ring #8: 1711
Number of black pixels in ring #9: 1460
Number of black pixels in ring #10: 1223
Number of black pixels in ring #11: 1505
Number of black pixels in ring #12: 1199
Number of black pixels in ring #13: 1120
Number of black pixels in ring #14: 1104
Number of black pixels in ring #15: 608
Number of black pixels in ring #16: 278
Number of black pixels in ring #17: 168
Number of black pixels in ring #18: 153
Number of black pixels in ring #19: 249
Number of black pixels in ring #20: 77

由于您正在处理网络摄像头数据,因此您可能需要修改 if pix[i,j] == (0,0,0): 行,因为完全黑色的像素非常罕见。您可以改为检查像素和纯黑色之间的 color difference 是否相当小。有几种计算方法,但欧氏距离是最简单的。

def color_diff(a, b):
    return math.sqrt(
        (a[0]-b[0])**2 + 
        (a[1]-b[1])**2 + 
        (a[2]-b[2])**2
    )

#later in the code...

if color_diff(pix[i,j], (0,0,0)) < some_tolerance_value_goes_here:
        results[band] += 1