Rgb image to the grayscale image

90 views Asked by At

I have an image of a laser beam in RGB format. I want to get the brightness of an image by converting it to grayscale.

But it turns out not what I planned. The center should be the brightest place, but it turns out dark help, who knows

enter image description here

enter image description here

from PIL import Image
import math

image = Image.open("/content/TiSa_fs_vert_1.jpg")
image = image.convert ('RGB')
width, height = image.size
y = 450

brightness_values = []

# Loop through the horizontal line
for x in range(width):
    pixelRGB = image.getpixel((x, y))
    R, G, B = pixelRGB
    #brightness = math.sqrt(R**2 + G**2 + B**2)
    brightness = (R + G + B)//3
    brightness_values.append(brightness)

print(brightness_values)
1

There are 1 answers

5
OM222O On

You're in luck since you're using a laser, it'll be monochrome and easy to seperate out from color channels

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import cv2

img = np.array(Image.open("laser.jpg"))

plt.figure()
plt.imshow(img)
plt.show()
# Since the laser is red, you can just take out the red channel from the RGB
# Color channels are 0=Red, 1=Green, 2=Blue
r=img[:,:,0]
plt.figure()
plt.imshow(r, cmap='grey') 
plt.show()

# To plot only the brightest portion of your selected channel, you can do:
threshold= r.max()*0.9
# set areas of the image that are below the threshold to be 0
r[np.where(r<threshold)]=0
# set areas of the image that are at or above the threshold to be 1
r[np.where(r>=threshold)]=1

plt.figure()
plt.imshow(r, cmap='grey')
plt.show()

# To clean up the image a bit more
cleaned_up = cv2.dilate(r,np.ones((3,3), dtype=np.uint8),iterations = 5)
plt.figure()
plt.imshow(cleaned_up, cmap='grey')
plt.show()

# Simplistic method to calculate center
# (you should probably apply some smoothing to the calculated brightness along each axis)
x_sum = cleaned_up.sum(axis=0)
y_sum = cleaned_up.sum(axis=1)
center = (x_sum.max(), y_sum.max())
plt.figure()
plt.plot(np.arange(x_sum.shape[0]),x_sum)
plt.plot(y_sum,np.arange(y_sum.shape[0]))
plt.show()

plt.figure()
plt.imshow(cleaned_up, cmap='grey')
plt.plot(center[0],center[1], 'ro')
plt.show()

# Using image moments to find the centroid
moments = cv2.moments(cleaned_up)
centroid = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
plt.figure()
plt.imshow(cleaned_up, cmap='grey')
plt.plot(centroid[0],centroid[1], 'ro')
plt.show()

to be perfectly honest both methods for finding the center work decently well and produce very similar results, but I prefer the centroid approach using image moments as it looks more centered to my eyes, but feel free to pick the one that works the best for you