'How to calculate average pixel intensity inside a laser line in Python?

I am trying to write a code that calculates the speckle contrast of a laser line. Here is an example of an image that I would be analyzing:

The image is black with white horizontal laser lines

1

My current code is able to calculate the speckle contrast of the entire image, but this is not very useful since I only need to know the speckle contrast of the actual laser line.

Here is my code for reference:

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

# Open and display the image

im = Image.open(r"Picture1.jpg")
im.show()

# Create a list of pixel intensity values 

sequence_of_pixels = im.getdata()
pi = list(sequence_of_pixels)

# Calculate the standard deviation of the image

stat = ImageStat.Stat(im)
standard_deviation, = stat.stddev
print("The standard deviation is: ", stat.stddev)

# Take the spatial averaging operator on pi and pi_squared 

pi_bracket = statistics.mean(pi)
print("The average pixel value is: ",pi_bracket)

# Next take the list of pixel values and square each value
# This makes a list of the squared elements of the original list of pixel values

def square(number):
    return number**2
squaring_iterator = map(square, pi)
pi_squared = list(squaring_iterator)

# Next take the average value of this new list 

pi_squared_bracket = statistics.mean(pi_squared)
print("The average squared pixel value is: ",pi_squared_bracket)

# Calculate the speckle average 
contrast = standard_deviation/pi_bracket
print("Speckle contrast is:", contrast)

My question is, how could I isolate the laser lines in the image so that I am only focusing on calculating the speckle contrast for that?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source