大恒相机-mono12-python示例程序
示例程序,开箱即用。
import gxipy as gx
from PIL import Image
import datetime
from gxipy.gxidef import *
SN = "xxxx" #输入你的sn序列号def reconnect_callback():
# 收到重连通知,用户根据需求进行操作…passdef disconnect_callback():# 收到断线通知,用户根据需求进行操作…passdef reconnect(cam):# 注册重连回调、断线回调cam.register_device_reconnect_callback(reconnect_callback)cam.register_device_disconnect_callback(disconnect_callback)# 开启断线重连功能local_device_feature = cam.get_local_device_feature_control()local_device_feature.get_bool_feature("EnableAutoConnection").set(True)# ......local_device_feature.get_bool_feature("EnableAutoConnection").set(False)# 注销重连回调、断线回调cam.unregister_device_reconnect_callback()cam.unregister_device_disconnect_callback()def check_color_support(cam):"""检查相机是否支持彩色图像"""try:remote_device_feature = cam.get_remote_device_feature_control()pixel_format_feature = remote_device_feature.get_enum_feature("PixelFormat")# 获取所有支持的像素格式# 使用正确的方法获取枚举值pixel_formats = pixel_format_feature.get_symbol_list() if hasattr(pixel_format_feature, 'get_symbol_list') else []if not pixel_formats:# 如果get_symbol_list方法不存在,尝试其他方式print("无法获取像素格式列表,尝试设置彩色格式测试...")try:# 尝试设置一个常见的彩色格式pixel_format_feature.set("BayerRG8")print("相机支持BayerRG8格式,可能支持彩色图像")# 恢复原来的设置pixel_format_feature.set("Mono12")return Trueexcept:print("相机不支持BayerRG8格式")return Falseprint("支持的像素格式:")color_formats = []mono_formats = []# 常见的彩色和黑白像素格式color_format_names = ["Bayer", "RGB", "BGR", "YUV", "Color"]mono_format_names = ["Mono8", "Mono10", "Mono12", "Mono14", "Mono16"]for format_name in pixel_formats:is_color = any(color_name in format_name for color_name in color_format_names)is_mono = any(mono_name in format_name for mono_name in mono_format_names)if is_color:color_formats.append(format_name)elif is_mono:mono_formats.append(format_name)print(f" {format_name}")print(f"\n彩色格式数量: {len(color_formats)}")print(f"黑白格式数量: {len(mono_formats)}")if len(color_formats) > 0:print("相机支持彩色图像")return Trueelse:print("相机不支持彩色图像")return Falseexcept Exception as e:print(f"检查相机彩色支持时出错: {e}")return Falsedef frame_info(raw_image):print("图像信息:")print(f" Frame ID: {raw_image.get_frame_id()}")print(f" Width: {raw_image.get_width()}")print(f" Height: {raw_image.get_height()}")pixel_format = raw_image.get_pixel_format()print(f" Pixel Format: {pixel_format}")print(f" Image Size: {raw_image.get_image_size()}")# 根据像素格式判断位深度# Mono12的像素格式值通常是17825797if pixel_format == 17825797: # GX_PIXEL_FORMAT_MONO12bits_per_pixel = 12print(" 图像位深度: 12位")elif pixel_format == 17301505: # GX_PIXEL_FORMAT_MONO8bits_per_pixel = 8print(" 图像位深度: 8位")else:bits_per_pixel = "未知"print(f" 图像位深度: 未知 ({pixel_format})")def main():Width_set = 4024 # 设置分辨率宽Height_set = 3036 # 设置分辨率高framerate_set = 3 # 设置帧率num = 10 # 采集帧率次数(为调试用,可把后边的图像采集设置成while循环,进行无限制循环采集)#打印print("")print("###############################################################")print(" 连续获取mono图像并显示获取的图像.")print("###############################################################")print("")print("摄像机初始化......")print("")#创建设备device_manager = gx.DeviceManager() # 创建设备对象dev_num, dev_info_list = device_manager.update_device_list() #枚举设备,即枚举所有可用的设备if dev_num == 0:print("Number of enumerated devices is 0")returnelse:print("")print("**********************************************************")print("创建设备成功,设备号为:%d" % dev_num)#通过设备序列号打开一个设备cam = device_manager.open_device_by_sn(SN)# 检查相机是否支持彩色图像print("")print("**********************************************************")print("检查相机彩色图像支持情况:")is_color_supported = check_color_support(cam)print("**********************************************************")#设置宽和高# set resolutioncam.Width.set(Width_set)cam.Height.set(Height_set)remote_device_feature = cam.get_remote_device_feature_control()remote_device_feature.get_enum_feature("PixelFormat").set("Mono12")value, str_value = remote_device_feature.get_enum_feature("PixelFormat").get()print("current PixelFormat is: ",str_value)exposure_time_feature = remote_device_feature.get_float_feature("ExposureTime")exposure_time_feature.set(100000.0)print(f"curretn exposure time: {exposure_time_feature.get()}")cam.TriggerMode.set(gx.GxSwitchEntry.ON)cam.TriggerSource.set(gx.GxTriggerSourceEntry.SOFTWARE)# trigger_soft_ware_feature = remote_device_feature.get_register_feature("TriggerSoftware")# 发送命令:软触发# trigger_soft_ware_feature.send_command()# image_convert = device_manager.create_image_format_convert()#设置连续采集#cam.TriggerMode.set(gx.GxSwitchEntry.OFF) # 设置触发模式# cam.AcquisitionFrameRateMode.set(gx.GxSwitchEntry.ON)#设置帧率cam.AcquisitionFrameRate.set(framerate_set)print("")print("**********************************************************")print("用户设置的帧率为:%d fps"%framerate_set)framerate_get = cam.CurrentAcquisitionFrameRate.get() #获取当前采集的帧率print("当前采集的帧率为:%d fps"%framerate_get)#开始数据采集print("")print("**********************************************************")print("开始数据采集......")print("")cam.stream_on()#采集图像for i in range(num):# 发送软件触发命令cam.TriggerSoftware.send_command()raw_image = cam.data_stream[0].get_image() # 打开第0通道数据流if raw_image is None:print("获取原始图像失败.")continue# 打印图像信息,包括位深度# frame_info(raw_image)numpy_image = raw_image.get_numpy_array()# rgb_image = raw_image.convert("RGB") # 从彩色原始图像获取RGB图像#rgb_image.image_improvement(color_correction_param, contrast_lut, gamma_lut) # 实现图像增强# numpy_image = rgb_image.get_numpy_array() # 从RGB图像数据创建numpy数组if numpy_image is None:print("转换numpy数组失败.")continue# img = Image.fromarray(numpy_image, 'RGB') # 展示获取的图像img = Image.fromarray(numpy_image, 'L')# img.show()mtime = datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')img.save( str(i) + str("-") + mtime + ".jpg") # 保存图片到本地print("Frame ID: %d Height: %d Width: %d framerate_set:%dfps framerate_get:%dfps"% (raw_image.get_frame_id(), raw_image.get_height(), raw_image.get_width(), framerate_set, framerate_get)) # 打印采集的图像的高度、宽度、帧ID、用户设置的帧率、当前采集到的帧率#停止采集print("")print("**********************************************************")print("摄像机已经停止采集")cam.stream_off()#关闭设备print("")print("**********************************************************")print("系统提示您:设备已经关闭!")cam.close_device()if __name__ == "__main__":main()