Reputation: 39
I am looking to create a simple code that will allow me to analyse an image taken using the raspberry pi camera.
I want to use python or raspbarian to split an image into concentric rings/annulus rings and then analyse the number of black pixels in each ring.
Any advice would be great!
Upvotes: 0
Views: 93
Reputation: 76194
I don't know much about the Rapberry Pi, but I assume you can access images from its camera as an ordinary image file, and I assume you can install PIL.
If so, you can open the image, iterate over its pixels, and categorize each pixel into a band based on its distance from the center.
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}")
Let's try running this on this sample image:
Result:
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
Since you're working with webcam data, you're probably going to need to modify the if pix[i,j] == (0,0,0):
line, since perfectly black pixels will be quite rare. You could instead check that the color difference between your pixel and pure black is reasonably small. There are several ways to calculate this, but Euclidean distance is easiest.
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
Upvotes: 1