同心环树莓派

时间:2018-06-28 12:17:15

标签: python image-processing raspberry-pi buffer

我正在寻找创建一个简单的代码,使我能够分析使用树莓派相机拍摄的图像。

我想使用python或raspbarian将图像拆分为同心环/环形环,然后分析每个环中的黑色像素数。

任何建议都会很棒!

1 个答案:

答案 0 :(得分:1)

我对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}")

让我们尝试在此示例图像上运行它:

enter image description here

结果:

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
相关问题