• python调用海康工业相机实现拍一张图片,支持调整曝光、增益、帧率


    使用的时候,只需要修改导入的MvImport库的位置就好了,这个库是下载windows 的mvs客户端带着的,
    调整曝光、增益、帧率去125行自己修改

    # -- coding: utf-8 --
    
    import sys
    import copy
    import msvcrt
    
    from ctypes import *
    import time
    import datetime
    
    
    
    # sys.path.append("../MvImport")
    sys.path.append("F:\\APP\\haikang20230906\\MVS\\Development\\Samples\\Python\\MvImport")
    
    from MvCameraControl_class import *
    
    def save_bmp_img(save_bmg_path):
        # 获取当前日期和时间
        current_datetime = datetime.datetime.now()
    
        # 格式化日期和时间为指定格式
        formatted_datetime = current_datetime.strftime("%Y_%m_%d_%H_%M_%S")
    
        print("当前日期和时间:", formatted_datetime)
        #下边的函数进行拍一张照
        deviceList = MV_CC_DEVICE_INFO_LIST()
        tlayerType = MV_GIGE_DEVICE | MV_USB_DEVICE
    
        # ch:枚举设备 | en:Enum device
        ret = MvCamera.MV_CC_EnumDevices(tlayerType, deviceList)
        if ret != 0:
            print("enum devices fail! ret[0x%x]" % ret)
            sys.exit()
    
        if deviceList.nDeviceNum == 0:
            print("find no device!")
            sys.exit()
    
        print("find %d devices!" % deviceList.nDeviceNum)
    
        for i in range(0, deviceList.nDeviceNum):
            mvcc_dev_info = cast(deviceList.pDeviceInfo[i], POINTER(MV_CC_DEVICE_INFO)).contents
            if mvcc_dev_info.nTLayerType == MV_GIGE_DEVICE:
                print("\ngige device: [%d]" % i)
                strModeName = ""
                for per in mvcc_dev_info.SpecialInfo.stGigEInfo.chModelName:
                    strModeName = strModeName + chr(per)
                print("device model name: %s" % strModeName)
    
                nip1 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0xff000000) >> 24)
                nip2 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x00ff0000) >> 16)
                nip3 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x0000ff00) >> 8)
                nip4 = (mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x000000ff)
                print("current ip: %d.%d.%d.%d\n" % (nip1, nip2, nip3, nip4))
            elif mvcc_dev_info.nTLayerType == MV_USB_DEVICE:
                print("\nu3v device: [%d]" % i)
                strModeName = ""
                for per in mvcc_dev_info.SpecialInfo.stUsb3VInfo.chModelName:
                    if per == 0:
                        break
                    strModeName = strModeName + chr(per)
                print("device model name: %s" % strModeName)
    
                strSerialNumber = ""
                for per in mvcc_dev_info.SpecialInfo.stUsb3VInfo.chSerialNumber:
                    if per == 0:
                        break
                    strSerialNumber = strSerialNumber + chr(per)
                print("user serial number: %s" % strSerialNumber)
    
        nConnectionNum = 0
        # 默认使用0这个相机
        # nConnectionNum = input("please input the number of the device to connect:")
    
        if int(nConnectionNum) >= deviceList.nDeviceNum:
            print("intput error!")
            sys.exit()
    
        # ch:创建相机实例 | en:Creat Camera Object
        cam = MvCamera()
    
        # ch:选择设备并创建句柄 | en:Select device and create handle
        stDeviceList = cast(deviceList.pDeviceInfo[int(nConnectionNum)], POINTER(MV_CC_DEVICE_INFO)).contents
    
        ret = cam.MV_CC_CreateHandle(stDeviceList)
        if ret != 0:
            print("create handle fail! ret[0x%x]" % ret)
            sys.exit()
    
        # ch:打开设备 | en:Open device
        ret = cam.MV_CC_OpenDevice(MV_ACCESS_Exclusive, 0)
        if ret != 0:
            print("open device fail! ret[0x%x]" % ret)
            sys.exit()
    
        # ch:探测网络最f佳包大小(只对GigE相机有效) | en:Detection network optimal package size(It only works for the GigE camera)
        if stDeviceList.nTLayerType == MV_GIGE_DEVICE:
            nPacketSize = cam.MV_CC_GetOptimalPacketSize()
            if int(nPacketSize) > 0:
                ret = cam.MV_CC_SetIntValue("GevSCPSPacketSize", nPacketSize)
                if ret != 0:
                    print("Warning: Set Packet Size fail! ret[0x%x]" % ret)
            else:
                print("Warning: Get Packet Size fail! ret[0x%x]" % nPacketSize)
    
        # ch:设置触发模式为off | en:Set trigger mode as off
        ret = cam.MV_CC_SetEnumValue("TriggerMode", MV_TRIGGER_MODE_OFF)
        if ret != 0:
            print("set trigger mode fail! ret[0x%x]" % ret)
            sys.exit()
    
        # ch:获取数据包大小 | en:Get payload size
        stParam = MVCC_INTVALUE()
        memset(byref(stParam), 0, sizeof(MVCC_INTVALUE))
    
        ret = cam.MV_CC_GetIntValue("PayloadSize", stParam)
        if ret != 0:
            print("get payload size fail! ret[0x%x]" % ret)
            sys.exit()
        nPayloadSize = stParam.nCurValue
    
        # ch:开始取流 | en:Start grab image
        start_time = time.time()
        #设置曝光时间 单位毫秒 我一般用20000左右
        cam.MV_CC_SetFloatValue("ExposureTime", float(20000))
        #设置图像增益,我一般用5左右
        cam.MV_CC_SetFloatValue("Gain", float(5))
        #设置帧率,我一般就用默认,这款相机好像是74帧率
        cam.MV_CC_SetFloatValue("AcquisitionFrameRate", float(74))
        ret = cam.MV_CC_StartGrabbing()
        if ret != 0:
            print("start grabbing fail! ret[0x%x]" % ret)
            sys.exit()
        stDeviceList = MV_FRAME_OUT_INFO_EX()
        memset(byref(stDeviceList), 0, sizeof(stDeviceList))
        data_buf = (c_ubyte * nPayloadSize)()
        ret = cam.MV_CC_GetOneFrameTimeout(byref(data_buf), nPayloadSize, stDeviceList, 1000)
        if ret == 0:
            # Stop = time()
            # print(Stop - start)
            print("get one frame: Width[%d], Height[%d], nFrameNum[%d]" % (
                stDeviceList.nWidth, stDeviceList.nHeight, stDeviceList.nFrameNum))
    
            stConvertParam = MV_SAVE_IMAGE_PARAM_EX()
            stConvertParam.nWidth = stDeviceList.nWidth
            stConvertParam.nHeight = stDeviceList.nHeight
            stConvertParam.pData = data_buf
            stConvertParam.nDataLen = stDeviceList.nFrameLen
            stConvertParam.enPixelType = stDeviceList.enPixelType
    
    
            # MV_Image_Undefined  = 0, //未定义
            #   MV_Image_Bmp        = 1, //BMP图片
            #   MV_Image_Jpeg       = 2, //JPEG图片
            #   MV_Image_Png        = 3, //PNG图片,暂不支持
            #   MV_Image_Tif        = 4, //TIF图片,暂不支持
    
            # jpg参数
            # stConvertParam.nJpgQuality   = 99  # 压缩质量选择范围[50-99]
            # file_path = "save.jpg"
            # stConvertParam.enImageType = MV_Image_Jpeg
            # bmpsize = nPayloadSize
    
            file_path = save_bmg_path+formatted_datetime+".bmp"
            stConvertParam.enImageType = MV_Image_Bmp
    
            bmpsize = stDeviceList.nWidth * stDeviceList.nHeight * 3 + 54
    
            stConvertParam.nBufferSize = bmpsize
            bmp_buf = (c_ubyte * bmpsize)()
            stConvertParam.pImageBuffer = bmp_buf
    
            ret = cam.MV_CC_SaveImageEx2(stConvertParam)
            if ret != 0:
                print("save file executed failed0:! ret[0x%x]" % ret)
                del data_buf
                sys.exit()
            end_time = time.time()
            print(start_time - end_time)
            # print(stop - start)
            file_open = open(file_path.encode('ascii'), 'wb+')
            try:
                img_buff = (c_ubyte * stConvertParam.nImageLen)()
                cdll.msvcrt.memcpy(byref(img_buff), stConvertParam.pImageBuffer, stConvertParam.nImageLen)
                file_open.write(img_buff, )
                print(img_buff)
            except:
                raise Exception("save file executed failed1::%s" % e.message)
            finally:
                file_open.close()
    
    
        else:
            print("get one frame fail, ret[0x%x]" % ret)
    
        # ch:停止取流 | en:Stop grab image
        ret = cam.MV_CC_StopGrabbing()
        if ret != 0:
            print("stop grabbing fail! ret[0x%x]" % ret)
            del data_buf
            sys.exit()
    
        # ch:关闭设备 | Close device
        ret = cam.MV_CC_CloseDevice()
        if ret != 0:
            print("close deivce fail! ret[0x%x]" % ret)
            del data_buf
            sys.exit()
    
        # ch:销毁句柄 | Destroy handle
        ret = cam.MV_CC_DestroyHandle()
        if ret != 0:
            print("destroy handle fail! ret[0x%x]" % ret)
            del data_buf
            sys.exit()
    
        del data_buf
        return file_path
    if __name__ == "__main__":
        save_bmp_path = './hik_cam_img/'
        ret_save_path =     save_bmp_img(save_bmp_path)
        print("ret_save_path",ret_save_path)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
  • 相关阅读:
    CSS常见选择器
    数据结构系列学习(九) - 循环队列(Circular_Queue)
    【GA-LSSVM预测】基于遗传算法优化最小二乘支持向量机的回归预测(MATLAB代码实现)
    分布式事务----seata
    使用 Redis 和 Lua 实现分布式锁
    (十九)Spring中的八大模式
    项目管理之六大目标及成功方程式
    Git常用命令与分支管理
    Spring AOP(JavaEE进阶系列5)
    TRC心血管研究之艾美捷TRC缺血研究领域
  • 原文地址:https://blog.csdn.net/weixin_44298961/article/details/134014178