Skip to content
Snippets Groups Projects

Camera sensor scripts

Merged Imported hb2n21 requested to merge Camera_sensor into main
3 files
+ 637
0
Compare changes
  • Side-by-side
  • Inline
Files
3
+ 179
0
"""
Created on Wed Jul 10 15:46:53 2024
@author: pi
"""
# Script to measure laser beam wwidth from image (very early stages)
from pyueye import ueye
import numpy as np
import matplotlib.pyplot as plt
import paho.mqtt.client as mqtt
import json, base64, random, string, math, datetime
import imageio.v3 as iio
import laserbeamsize as lbs
##Following functions taken from cam3v4.py
# this converts the image to something I can transmit
def convertImageToBase64():
"""convert image file to base 64
Returns:
_type_: _description_
"""
with open("foo.jpg", "rb") as image_file:
base64_bytes = base64.b64encode(image_file.read())
encoded = base64_bytes.decode()
return encoded
def randomword(length):
"""_summary_
Args:
length (int): length of string
Returns:
_type_: _description_
"""
return ''.join(random.choice(string.ascii_lowercase) for i in range(length))
def publishEncodedImage(encoded):
"""_summary_
Args:
encoded (_type_): _description_
"""
end = packet_size
start = 0
length = len(encoded)
picId = randomword(8)
pos = 0
no_of_packets = math.ceil(length/packet_size)
while start <= len(encoded):
data = {"data": encoded[start:end], "pic_id":picId, "pos": pos, "size": no_of_packets}
client.publish("tsunami/beam_image",json.JSONEncoder().encode(data))
end += packet_size
start += packet_size
pos = pos +1
def take_image(width, height):
"""_summary_
Args:
width (_type_): _description_
height (_type_): _description_
Returns:
_type_: _description_
"""
h_cam = ueye.HIDS(0)
if ueye.is_InitCamera(h_cam, None) != ueye.IS_SUCCESS:
print("Failed to initialise camera.")
return
if ueye.is_EnableAutoExit(h_cam, 1) != ueye.IS_SUCCESS:
print ("Failed to enable auto exit.")
return
if ueye.is_SetColorMode(h_cam, ueye.IS_CM_SENSOR_RAW8) != ueye.IS_SUCCESS:
print ("Failed to set color mode.")
return
if ueye.is_SetExternalTrigger(h_cam, ueye.IS_SET_TRIGGER_SOFTWARE):
print ("Failed to set external trigger.")
return
mem_ptr = ueye.c_mem_p()
mem_id = ueye.int()
if ueye.is_AllocImageMem(h_cam, width, height, 8, mem_ptr, mem_id) != ueye.IS_SUCCESS:
print ("Failed to allocate image memory.")
return
ueye.is_SetImageMem(h_cam, mem_ptr, mem_id)
image_data = np.ones((height, width), dtype = np.uint8)
ueye.is_FreezeVideo(h_cam, ueye.IS_GET_LIVE)
ueye.is_CopyImageMem(h_cam, mem_ptr, mem_id, image_data.ctypes.data)
if ueye.is_ExitCamera(h_cam) != ueye.IS_SUCCESS:
print ("Failed to exit camera.")
return image_data
def on_publish(client, userdata, result):
"""_summary_
Args:
client (_type_): _description_
userdata (_type_): _description_
result (_type_): _description_
"""
print("data published\n")
pass
#%% setup mqtt broker
broker_address = "iotgate.ecs.soton.ac.uk"
client = mqtt.Client()
client.on_publish = on_publish
client.will_set('tsunami/camera_status', 'Camera feed failed ungracefully: pls restart')
packet_size=3000
im1 = take_image(1280, 1024)
timestr = datetime.datetime.now().replace(microsecond=0).isoformat(' ')
ff = plt.figure()
xsum = im1.sum(axis=0)
ysum = im1.sum(axis=1)
fullsum = im1.sum(dtype = float)
print( fullsum )
if fullsum==0:
no_camera = 1
print('no camera signal')
else:
no_camera = 0
print('Camera signal OK')
threshold=1.7e6 #sum you get when the laser is on...
if fullsum < threshold:
no_signal = 1
print('no laser signal')
else:
no_signal=0
print('laser on')
xpeak_index = 600
ypeak_index = 500
if no_signal ==0:
x_pi = np.argmax(xsum)
xpeak_index = x_pi.astype(np.float64)
y_pi = np.argmax(ysum)
ypeak_index = y_pi.astype(np.float64)
print("x peak posn:", xpeak_index)
print("y peak posn:", ypeak_index)
plt.plot(xpeak_index, ypeak_index, 'ro')
plt.axvline(x = xpeak_index)
plt.axhline(y=ypeak_index)
plt.title('Tsunami Beam image, '+timestr)
ff.savefig("foo.jpg")
#%% Analysis of beam width
image = iio.imread("foo.jpg")
x, y, dx, dy, phi = lbs.beam_size(image)
print("The centre of the beam ellipse is at (%.0f, %.0f)" % (x, y))
print("The ellipse diameter (closest to horizontal) is %.0f pixels" % dx)
print("The ellipse diameter (closest to vertical) is %.0f pixels" % dy)
print("The ellipse is rotated %.0f degrees ccw from the horizontal" % (phi * 180/3.1416))
Loading