大恒相机-mono12-python示例程序

示例程序,开箱即用。

python 复制代码
import gxipy as gx
from PIL import Image
import datetime
from gxipy.gxidef import *
SN = "xxxx" #输入你的sn序列号

def reconnect_callback():
# 收到重连通知,用户根据需求进行操作...
    pass


def disconnect_callback():
    # 收到断线通知,用户根据需求进行操作...
    pass
 

def 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 True
            except:
                print("相机不支持BayerRG8格式")
                return False
        
        print("支持的像素格式:")
        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 True
        else:
            print("相机不支持彩色图像")
            return False
            
    except Exception as e:
        print(f"检查相机彩色支持时出错: {e}")
        return False

def 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的像素格式值通常是17825797
    if pixel_format == 17825797:  # GX_PIXEL_FORMAT_MONO12
        bits_per_pixel = 12
        print("  图像位深度: 12位")
    elif pixel_format == 17301505:  # GX_PIXEL_FORMAT_MONO8
        bits_per_pixel = 8
        print("  图像位深度: 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")
        return
    else:
        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 resolution
    cam.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()
相关推荐
后端小张2 小时前
【JAVA 进阶】SpringAI人工智能框架深度解析:从理论到实战的企业级AI应用开发指南
java·开发语言·人工智能
麦烤楽鸡翅2 小时前
小红书推荐系统(牛客)
java·python·算法·秋招·春招·牛客·面试算法题
MATLAB代码顾问2 小时前
MATLAB实现CNN(卷积神经网络)图像边缘识别
开发语言·matlab·cnn
FJW0208142 小时前
Python函数
开发语言·python
屁股割了还要学2 小时前
【C++进阶】STL-string的简单实现
c语言·开发语言·数据结构·c++·学习·考研
superlls2 小时前
(Java基础)集合框架继承体系
java·开发语言
ad钙奶长高高2 小时前
【C语言】原码反码补码详解
c语言·开发语言
mortimer3 小时前
如何解决 uv run 因网络问题导致的 Python 下载失败
python·github