Ejemplo n.º 1
0
    def camera_setup(self):
        # create a device manager
        self.device_manager = gx.DeviceManager()
        self.dev_num, self.dev_info_list = self.device_manager.update_device_list()

        if self.dev_num is 0:
            print("Number of enumerated devices is 0")
            return
        
        # open the first device
        self.cam = self.device_manager.open_device_by_index(1)

        # set Width
        self.cam.Width.set(1440)

        # set Height
        self.cam.Height.set(1080)

        # offset width
        self.cam.OffsetX.set(0)

        # offset width
        self.cam.OffsetY.set(0)
    
        # set continuous acquisition
        self.cam.TriggerMode.set(gx.GxSwitchEntry.OFF)

        # set exposure
        self.cam.ExposureTime.set(10000.0)

        # set gain
        self.cam.Gain.set(24.0)

        # set auto white balance
        self.cam.BalanceWhiteAuto.set(1)

        # User Set Selector
        self.cam.UserSetSelector.set(1)
        self.cam.UserSetSave.send_command()

        # get param of improving image quality
        if self.cam.GammaParam.is_readable():
            gamma_value = self.cam.GammaParam.get()
            self.gamma_lut = gx.Utility.get_gamma_lut(gamma_value)
        else:
            self.gamma_lut = None

        if self.cam.ContrastParam.is_readable():
            contrast_value = self.cam.ContrastParam.get()
            self.contrast_lut = gx.Utility.get_contrast_lut(contrast_value)
        else:
            self.contrast_lut = None

        if self.cam.ColorCorrectionParam.is_readable():
            self.color_correction_param = self.cam.ColorCorrectionParam.get()
        else:
            self.color_correction_param = 0

        # set the acq buffer count
        self.cam.data_stream[0].set_acquisition_buffer_number(2)
def main():
    # print the demo information
    print("")
    print("-------------------------------------------------------------")
    print(
        "Sample to show how to acquire mono or color image continuously according to camera type "
        "and show acquired image.")
    print("-------------------------------------------------------------")
    print("")
    print("Initializing......")
    print("")

    # create a device manager
    device_manager = gx.DeviceManager()
    dev_num, dev_info_list = device_manager.update_device_list()
    if dev_num is 0:
        print("Error: Number of enumerated devices is 0")
        return

    # open the first device
    cam = device_manager.open_device_by_index(1)

    # set exposure / 노출값(exposure Time) default
    cam.ExposureTime.set(10000)

    # set gain / 선명도 조절 default
    cam.Gain.set(5.0)

    # send software trigger command
    cam.TriggerMode.set(gx.GxSwitchEntry.ON)
    cam.TriggerSource.set(gx.GxTriggerSourceEntry.SOFTWARE)

    # start data acquisition
    cam.stream_on()

    # 트렉바 생성
    cv2.namedWindow('trackbarwindow')
    cv2.createTrackbar('exposure', 'trackbarwindow', 10000, 100000, nothing)
    cv2.createTrackbar('gain', 'trackbarwindow', 5, 255, nothing)

    while True:

        # 트렉바 적용, 노출값(exposure Time) 조절, 선명도 트렉바 컨트롤
        exposure = cv2.getTrackbarPos('exposure', 'trackbarwindow')
        gain = cv2.getTrackbarPos('gain', 'trackbarwindow')
        cam.ExposureTime.set(exposure)
        cam.Gain.set(gain)

        # camera is color / 컬러일 때
        if cam.PixelColorFilter.is_implemented() is True:
            acq_color(cam, 1)
        # camera is mono / 모노일 때
        else:
            frame = acq_mono(cam, 10)
            cv2.imshow('array', frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):  #  'q'를 누르면 종료.
            cam.stream_off()  # stop acquisition
            cam.close_device()  # close device
            break
Ejemplo n.º 3
0
    def __init__(self):
        super(QThread, self).__init__()
        super(QThread, self).__init__()
        self.isRunning = False

        self.device_manager = gx.DeviceManager()

        self.camera = None
        self.exposure = None
        self.img_shape = [None, None]

        self.img_ranges = [None, None, None, None]
        self.calibr = [None, None]

        self.isProfile = False
        self.isCalcParams = False

        self.configfile = 'config.ini'
        self.config = configparser.ConfigParser()

        self.lastFrame = None
        self.exposure_changed = False

        self.pvs = {'prefix' : None, 'pos_x' : None, 'pos_y' : None}
        self.server = None
        self.drv = None
        self.server_thread = None

        self.isAvg = False
        self.avgFrames = 1
        self.avgDelay = 0
Ejemplo n.º 4
0
    def camera_init(self):
        self.device_manager = gx.DeviceManager()
        dev_num, dev_info_list = self.device_manager.update_device_list()
        if dev_num == 0:
            sys.exit(1)

        strSN = dev_info_list[0].get("sn")

        self.cam = self.device_manager.open_device_by_sn(strSN)
        self.cam.stream_on()
Ejemplo n.º 5
0
def init_camera(cam_ip=None,
                width=1920,
                height=1200,
                auto_expose=True,
                auto_balance=True):
    import gxipy as gx
    global cam
    global device_manager

    try:
        if cam_ip is None:
            # Create a device manager.
            device_manager = gx.DeviceManager()
            dev_num, dev_info_list = device_manager.update_device_list()
            if dev_num == 0:
                print('没有找到可用设备。')
                return False

            # Get the first cam's IP address.
            cam_ip = dev_info_list[0].get("ip")

        # Open the device.
        print('打开网络相机 (IP: {}), 进程PID: {}.'.format(cam_ip, os.getpid()))
        cam = device_manager.open_device_by_ip(cam_ip)
        print('打开网络相机 (IP: {}), 进程PID: {}.'.format(cam_ip, os.getpid()))

        # Set continues acquisition.
        cam.TriggerMode.set(gx.GxSwitchEntry.OFF)

        # Set the cam Height and Width.
        cam.Width.set(width)
        cam.Height.set(height)

        # Set exposure
        if auto_expose:
            cam.ExposureAuto.set(1)
        else:
            cam.ExposureAuto.set(0)
            cam.ExposureTime.set(200.0)

        # set gain.
        cam.Gain.set(10.0)

        if auto_balance:
            cam.BalanceWhiteAuto.set(1)
        else:
            cam.BalanceWhiteAuto.set(0)

        # Start data acquisition.
        cam.stream_on()
    except Exception as expt:
        print("Error: ", expt)
        return
Ejemplo n.º 6
0
def init_camera(cam_ip=None,
                width=1920,
                height=1200,
                auto_expose=True,
                auto_balance=True):
    import gxipy as gx
    global cam
    global device_manager

    # Create a device manager.
    device_manager = gx.DeviceManager()
    dev_num, dev_info_list = device_manager.update_device_list()
    if dev_num == 0 or len(dev_info_list) == 0:
        print('没有找到可用的GigE设备。')
        raise IOError('没有找到可用的GigE设备。')

    print("找到{}台设备:{}。".format(dev_num, dev_info_list))

    if cam_ip is None or cam_ip == "":
        # Get the first cam's IP address.
        cam_ip = dev_info_list[0].get("ip")
        print("未指定IP,使用: {}".format(dev_info_list[0].get("ip")))

    # Open the device.
    print('打开网络相机 (IP: {}), 进程PID: {}.'.format(cam_ip, os.getpid()))
    cam = device_manager.open_device_by_ip(cam_ip)

    # Set continues acquisition.
    cam.TriggerMode.set(gx.GxSwitchEntry.OFF)

    # Set the cam Height and Width.
    cam.Width.set(width)
    cam.Height.set(height)

    # Set exposure
    if auto_expose:
        cam.ExposureAuto.set(1)
    else:
        cam.ExposureAuto.set(0)
        cam.ExposureTime.set(200.0)

    # set gain.
    cam.Gain.set(10.0)

    if auto_balance:
        cam.BalanceWhiteAuto.set(1)
    else:
        cam.BalanceWhiteAuto.set(0)

    # Start data acquisition.
    cam.stream_on()
Ejemplo n.º 7
0
def main():
    # print the demo information
    print("")
    print("-------------------------------------------------------------")
    print("Sample to show how to acquire mono or color image by soft trigger "
          "and show acquired image.")
    print("-------------------------------------------------------------")
    print("")
    print("Initializing......")
    print("")

    # create a device manager
    device_manager = gx.DeviceManager()
    dev_num, dev_info_list = device_manager.update_device_list()
    if dev_num is 0:
        print("Number of enumerated devices is 0")
        return

    # open the first device
    cam = device_manager.open_device_by_index(1)

    # set exposure
    cam.ExposureTime.set(10000)

    # set gain
    cam.Gain.set(10.0)

    if dev_info_list[0].get("device_class") == gx.GxDeviceClassList.USB2:
        # set trigger mode
        cam.TriggerMode.set(gx.GxSwitchEntry.ON)
    else:
        # set trigger mode and trigger source
        cam.TriggerMode.set(gx.GxSwitchEntry.ON)
        cam.TriggerSource.set(gx.GxTriggerSourceEntry.SOFTWARE)

    # start data acquisition
    cam.stream_on()

    # camera is color camera
    if cam.PixelColorFilter.is_implemented() is True:
        acq_color(cam, 1)
    # camera is mono camera
    else:
        acq_mono(cam, 1)

    # stop acquisition
    cam.stream_off()

    # close device
    cam.close_device()
Ejemplo n.º 8
0
def initCam():
    #global cam
    global device_manager

    # Create a device manager.
    device_manager = gx.DeviceManager()
    dev_num, dev_info_list = device_manager.update_device_list()
    if dev_num is 0:
        print('None device found. ')
        return

    print(dev_num)
    for item in dev_info_list:
        print(item)

    # Get the first cam's IP address.
    cam_ip = dev_info_list[0].get("ip")
    print('Now, open the first cam with IP address {}.'.format(cam_ip))

    # Open the first device.
    cam = device_manager.open_device_by_ip(cam_ip)

    # Set continues acquisition.
    cam.TriggerMode.set(gx.GxSwitchEntry.OFF)

    # Set the cam Height and Width.
    cam.Width.set(1920)
    cam.Height.set(1200)

    # Set exposure
    cam.ExposureTime.set(10000.0)

    # Set auto white-balance
    cam.BalanceWhiteAuto.set(1)

    # Set exposure
    #cam.ExposureTime.set(1000.0)
    cam.ExposureAuto.set(1)

    # set gain.
    cam.Gain.set(10.0)
    #cam.GainAuto.set(1)

    cam.BalanceWhiteAuto.set(1)

    # Start data acquisition.
    cam.stream_on()

    return cam
Ejemplo n.º 9
0
def ImageTaker():

    # 从大恒水星2相机获取图片
    device_manager = gx.DeviceManager()

    dev_num, dev_info_list = device_manager.update_device_list()

    # 未检测到设备
    if dev_num == 0:
        print("未检测到设备")

    else:
        print(dev_info_list)

    # 相机对象(取index为1的设备)
    cam = device_manager.open_device_by_index(1)

    # 开始采集图像
    cam.stream_on()

    raw_image = cam.data_stream[0].get_image()

    if raw_image is None:
        print("图像采集失败")

    else:
        print("Frame ID: {} | Height: {} | Width: {}".format(
            raw_image.get_frame_id(), raw_image.get_height(),
            raw_image.get_width()))

    numpy_image = raw_image.get_numpy_array()
    if numpy_image is None:
        print("NumPy数组转换失败")

    # 停止采集图像
    cam.stream_off()

    # 存储图片
    img_filename = "ugrow_" + datetime.now().strftime("%Y%m%d%H%M%S")
    cv2.imwrite("images/{}.jpg".format(img_filename), numpy_image)

    # 读取图片
    image = cv2.imread("images/{}.jpg".format(img_filename))

    return image, img_filename
Ejemplo n.º 10
0
    def camera_init(self):
        self._device_manager = gx.DeviceManager()
        dev_num, dev_info_list = self._device_manager.update_device_list()
        if dev_num == 0:
            sys.exit(1)
        strSN = dev_info_list[0].get("sn")
        self._cam = self._device_manager.open_device_by_sn(strSN)

        # set exposure
        self._cam.ExposureTime.set(10000)

        # set gain
        self._cam.Gain.set(10.0)

        # send software trigger command
        self._cam.TriggerMode.set(gx.GxSwitchEntry.ON)
        self._cam.TriggerSource.set(gx.GxTriggerSourceEntry.SOFTWARE)
        self._cam.stream_on()
        return self._cam
Ejemplo n.º 11
0
def main1():

    # Create a device manager.
    device_manager = gx.DeviceManager()
    dev_num, dev_info_list = device_manager.update_device_list()
    if dev_num is 0:
        print('None device found. ')
        return

    print(dev_num)
    for item in dev_info_list:
        print(item)

    # Get the first cam's IP address.
    cam_ip = dev_info_list[0].get("ip")
    print('Now, open the first cam with IP address {}.'.format(cam_ip))

    # Open the first device.
    cam = device_manager.open_device_by_ip(cam_ip)

    # Set continues acquisition.
    cam.TriggerMode.set(gx.GxSwitchEntry.OFF)

    # Set exposure
    #cam.ExposureTime.set(10000.0)
    cam.ExposureTime.set(20000.0)

    # set gain.
    cam.Gain.set(5.0)

    # Start data acquisition.
    cam.stream_on()

    cv.namedWindow("result", cv.WINDOW_NORMAL)
    #cv.resizeWindow("result", 640, 400)
    #cv.moveWindow("result", 100, 100)

    accum_time = 0
    curr_fps = 0
    fps = "FPS: ??"
    prev_time = time.time()
    time_stamp = time.time()
    frame_stamp = time.time()

    # Acquisition image.
    while True:
        print('ONE FRAME:  {:3.3f} ms'.format(
            (time.time() - frame_stamp) * 1000))
        frame_stamp = time.time()

        # Get raw image.
        raw_image = cam.data_stream[0].get_image()
        if raw_image is None:
            print("Getting image failed. ")
            continue
        print('Get a frame from cam:   {:3.3f} ms'.format(
            (time.time() - time_stamp) * 1000))
        time_stamp = time.time()

        # Get RGB image from raw image.
        rgb_image = raw_image.convert('RGB')
        if rgb_image is None:
            continue
        print('Convert frame to RGB:   {:3.3f} ms'.format(
            (time.time() - time_stamp) * 1000))
        time_stamp = time.time()

        # Convert RGB image to numpy array.
        numpy_image = rgb_image.get_numpy_array()
        if numpy_image is None:
            continue
        print('Convert frame to numpy: {:3.3f} ms'.format(
            (time.time() - time_stamp) * 1000))
        time_stamp = time.time()

        curr_time = time.time()
        exec_time = curr_time - prev_time
        prev_time = curr_time
        accum_time = accum_time + exec_time
        curr_fps = curr_fps + 1
        if accum_time > 1:
            accum_time = accum_time - 1
            fps = "FPS: " + str(curr_fps)
            curr_fps = 0
        cv.putText(numpy_image,
                   text=fps,
                   org=(30, 60),
                   fontFace=cv.FONT_HERSHEY_SIMPLEX,
                   fontScale=2,
                   color=(255, 255, 255),
                   thickness=2)

        cv.imshow('result', numpy_image)
        if cv.waitKey(1) & 0xFF == ord('q'):
            break

    cv.destroyAllWindows()

    # Stop the data aquisition.
    cam.stream_off()

    # close device.
    cam.close_device()
Ejemplo n.º 12
0
def main():
    # print the demo information
    print("")
    print("-------------------------------------------------------------")
    print("Sample to show how to acquire color image continuously and show acquired image.")
    print("-------------------------------------------------------------")
    print("")
    print("Initializing......")
    print("")

    # create a device manager
    device_manager = gx.DeviceManager()
    dev_num, dev_info_list = device_manager.update_device_list()
    if dev_num is 0:
        print("Number of enumerated devices is 0")
        return

    # open device by serial number
    cam = device_manager.open_device_by_sn(dev_info_list[0].get("sn"))

    # if camera is mono
    if cam.PixelColorFilter.is_implemented() is False:
        print("This sample does not support mono camera.")
        cam.close_device()
        return

    # set continuous acquisition
    cam.TriggerMode.set(gx.GxSwitchEntry.OFF)

    # set exposure
    cam.ExposureTime.set(10000.0)

    # set gain
    cam.Gain.set(10.0)

    # set param of improving image quality
    if cam.GammaParam.is_readable():
        gamma_value = cam.GammaParam.get()
        gamma_lut = gx.Utility.get_gamma_lut(gamma_value)
    else:
        gamma_lut = None
    if cam.ContrastParam.is_readable():
        contrast_value = cam.ContrastParam.get()
        contrast_lut = gx.Utility.get_contrast_lut(contrast_value)
    else:
        contrast_lut = None
    color_correction_param = cam.ColorCorrectionParam.get()

    # start data acquisition
    cam.stream_on()

    # acquisition image: num is the image number
    num = 1
    for i in range(num):
        # get raw image
        raw_image = cam.data_stream[0].get_image()
        if raw_image is None:
            print("Getting image failed.")
            continue

        # get RGB image from raw image
        rgb_image = raw_image.convert("RGB")
        if rgb_image is None:
            continue

        # improve image quality
        rgb_image.image_improvement(color_correction_param, contrast_lut, gamma_lut)

        # create numpy array with data from raw image
        numpy_image = rgb_image.get_numpy_array()
        if numpy_image is None:
            continue

        # show acquired image
        img = Image.fromarray(numpy_image, 'RGB')
        img.show()

        # print height, width, and frame ID of the acquisition image
        print("Frame ID: %d   Height: %d   Width: %d"
              % (raw_image.get_frame_id(), raw_image.get_height(), raw_image.get_width()))

    # stop data acquisition
    cam.stream_off()

    # close device
    cam.close_device()
Ejemplo n.º 13
0
def main():
    # print the demo information
    print("")
    print("-------------------------------------------------------------")
    print(
        "Sample to show how to acquire mono image continuously and show acquired image."
    )
    print("-------------------------------------------------------------")
    print("")
    print("Initializing......")
    print("")

    # create a device manager
    device_manager = gx.DeviceManager()
    dev_num, dev_info_list = device_manager.update_device_list()
    if dev_num is 0:
        print("Number of enumerated devices is 0")
        return

    # open the first device
    cam = device_manager.open_device_by_index(1)

    # exit when the camera is a color camera
    if cam.PixelColorFilter.is_implemented() is True:
        print("This sample does not support color camera.")
        cam.close_device()
        return

    # set continuous acquisition
    cam.TriggerMode.set(gx.GxSwitchEntry.OFF)

    # set exposure
    cam.ExposureTime.set(10000)

    # set gain
    cam.Gain.set(10.0)

    # start data acquisition
    cam.stream_on()

    # acquire image: num is the image number
    num = 1
    for i in range(num):
        # get raw image
        raw_image = cam.data_stream[0].get_image()
        if raw_image is None:
            print("Getting image failed.")
            continue

        # create numpy array with data from raw image
        numpy_image = raw_image.get_numpy_array()
        if numpy_image is None:
            continue

        # show acquired image
        img = Image.fromarray(numpy_image, 'L')
        img.show()

        # print height, width, and frame ID of the acquisition image
        print("Frame ID: %d   Height: %d   Width: %d" %
              (raw_image.get_frame_id(), raw_image.get_height(),
               raw_image.get_width()))

    # stop data acquisition
    cam.stream_off()

    # close device
    cam.close_device()
Ejemplo n.º 14
0
 def video_stream(self):
     # create a device manager
     device_manager = gx.DeviceManager()
     dev_num, dev_info_list = device_manager.update_device_list()
     if dev_num is 0:
         print('Number of enumerated devices is 0')
         return
     # open device by serial number(通过sn码获取相机对象)
     self.cam = device_manager.open_device_by_sn(dev_info_list[0].get("sn"))
     # if camera is mono(如果相机是单通道, 则关闭相机)
     if self.cam.PixelColorFilter.is_implemented() is False:
         print('This sample does not support mono camera.')
         self.cam.close_device()
         return
     # set continuous acquisition(连续触发模式)
     self.cam.TriggerMode.set(gx.GxSwitchEntry.OFF)
     # 白平衡设置(连续白平衡)
     self.cam.BalanceWhiteAuto.set(gx.GxAutoEntry.CONTINUOUS)
     '''120帧'''
     # 相机采集帧率(相机采集帧率设置为120)
     self.cam.AcquisitionFrameRate.set(self.frame_rate)
     # set exposure(曝光设置为8285, 通过相机帧率计算公司得到, 120帧对应曝光时间为120fps)
     self.cam.ExposureTime.set(8285.0)
     # set gain(设置增益, 调节相机亮度)
     self.cam.Gain.set(0.0)
     '''100帧'''
     # # 相机采集帧率(相机采集帧率设置为60)
     # self.cam.AcquisitionFrameRate.set(self.frame_rate)
     # # set exposure(曝光设置为9930, 通过相机帧率计算公司得到, 100帧对应曝光时间为100fps)
     # self.cam.ExposureTime.set(9930.0)
     # # set gain(设置增益, 调节相机亮度)
     # self.cam.Gain.set(1.0)
     '''60帧'''
     # # 相机采集帧率(相机采集帧率设置为60)
     # self.cam.AcquisitionFrameRate.set(self.frame_rate)
     # # set exposure(曝光设置为16580, 通过相机帧率计算公司得到, 60帧对应曝光时间为60fps)
     # self.cam.ExposureTime.set(16580.0)
     # # set gain(设置增益, 调节相机亮度)
     # self.cam.Gain.set(1.0)
     # set roi(设置相机ROI, 裁剪尺寸)
     self.cam.Width.set(self.video_width)  # 宽度
     self.cam.Height.set(self.video_height)  # 高度
     self.cam.OffsetX.set(int((1920 - self.video_width) / 2))  # 宽度偏移量
     self.cam.OffsetY.set(int((1200 - self.video_height) / 2))  # 高度偏移量
     # start data acquisition(开始相机流采集)
     self.cam.stream_on()
     # acquisition image: num is the image number
     while self.record_thread_flag is True:  # 只要标志为True, 摄像头一直工作
         raw_image = self.cam.data_stream[0].get_image()
         if raw_image is None:
             print('Getting image failed.')
             continue
         if self.record_flag is True:
             self.frame_id += 1
             # 获取当前帧id
             current_frame_id = raw_image.get_frame_id()
             self.frame_id_list.append(current_frame_id)
             if self.frame_id == 1:
                 self.last_frame_id = current_frame_id - 1
             # 处理图像raw_image
             Thread(target=self.get_frame, args=(raw_image, self.allow_start_flag,)).start()
         else:
             numpy_image = raw_image.get_numpy_array()
             image = cv2.cvtColor(np.asarray(numpy_image), cv2.COLOR_BayerBG2BGR)
             self.camera_image = self.un_distortion(image)
             time.sleep(0.003)
     # stop data acquisition
     self.cam.stream_off()
     # close device
     self.cam.close_device()
Ejemplo n.º 15
0
def Frame_acquire():
    # 参数设定
    Width_set = 640  # 设置分辨率宽
    Height_set = 480  # 设置分辨率高
    framerate_set = 80  # 设置帧率

    # 枚举设备
    device_manager = gx.DeviceManager()    # 函数返回值为设备数量
    # 枚举设备。dev_info_list 是设备信息列表,列表klp数为枚举到的设备个数,列表元素是字典,其中包含设备索引(index)、ip 信息(ip)等设备信息
    dev_num, dev_info_list = device_manager.update_device_list()
    # update_device_list使用子网枚举,只能枚举到局域网内的同一网段的千兆网相机
    print("检测到的设备数:", dev_num)

    if dev_num == 0:
        sys.exit(1)
    # 打开设备

    # 方法一
    # 获取设备基本信息列表
    # strSN = dev_info_list[0].get("sn")
    # 通过序列号打开设备
    # cam = device_manager.open_device_by_sn(strSN)

    # 方法二
    # 通过用户 ID 打开设备
    # strUserID = dev_info_list[0].get("user_id")
    # cam = device_manager.open_device_by_user_id(strUserID)

    # 方法三
    # 通过索引打开设备
    strIndex = dev_info_list[0].get("index")
    cam = device_manager.open_device_by_index(strIndex)
    # 下面为只针对千兆网相机使用的打开方式

    # 方法四
    # 通过 IP 地址打开设备
    # strIP = dev_info_list[3].get("ip")
    # cam = device_manager.open_device_by_ip(strIP)

    # 方法五
    # 通过 MAC 地址打开设备
    # strMAC = dev_info_list[0].get("mac")
    # cam = device_manager.open_device_by_mac(strMAC)

    # set exposure
    # cam.ExposureTime.set(10000)

    # 参数设定
    cam.Width.set(Width_set)
    cam.Height.set(Height_set)

    # 设置连续采集
    # cam.TriggerMode.set(gx.GxSwitchEntry.OFF) # 设置触发模式
    cam.AcquisitionFrameRateMode.set(gx.GxSwitchEntry.ON)

    # 设置帧率
    cam.AcquisitionFrameRate.set(framerate_set)

    framerate_get = cam.CurrentAcquisitionFrameRate.get()  # 获取当前采集的帧率
    print("当前采集的帧率为:%d fps" % framerate_get)

    # 开始采集
    print("")
    print("**********************************************************")
    print("开始数据采集......")
    print("")
    cam.stream_on()

    # ...........................................................................获取流通道个数
    # 如果 int_channel_num == 1,设备只有一个流通道,列表 data_stream 元素个数为 1
    # 如果 int_channel_num > 1,设备有多个流通道,列表 data_stream 元素个数大于 1
    # 目前千兆网相机、USB3.0、USB2.0 相机均不支持多流通道。
    # int_channel_num = cam.get_stream_channel_num()
    # 获取数据

    # num 为采集图片次数
    num = 6
    t = 0
    print("采集图片次数:", num)
    for i in range(num):
        # 从第 0 个流通道获取一副图像  MER-500-GM只有一个灰色gray通道
        raw_image = cam.data_stream[0].get_image()

        if raw_image is None:
            print("获取彩色原始图像失败.")
            continue

        # 从彩色原始图像获取 RGB 图像
        rgb_image = raw_image.convert("RGB")
        if rgb_image is None:
            continue

        # 从 RGB 图像数据创建 numpy 数组
        numpy_image = rgb_image.get_numpy_array()

        if numpy_image is None:
            continue

        img = Image.fromarray(numpy_image, 'RGB')
        # img.show()

        mtime = datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')
        # 保存图片到本地
        # img.save(r"D:\PyCharm Community Edition 2019.3.3\project\Python SDK\\" + str(i) + str("-") + mtime + ".jpg")

        img.save("test_image.jpg")
        t += 1
        print("circel次数:", t)

        # 打印采集的图像的高度、宽度、帧ID、用户设置的帧率、当前采集到的帧率
        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))
    # Function recursive
    # Timer(1, Frame_acquire).start()

    cam.stream_off()
    cam.close_device()
Ejemplo n.º 16
0
    def __init__(self, mode = 'file', file = None, cam_ip = None, auto_expose = True, width = 1920, height = 1080, record = False, out_file = None):
        
        if mode == 'file':
            self.vid = cv2.VideoCapture(file)
            if not self.vid.isOpened():
                raise IOError("打开文件或本地相机失败: {}".format(input))

            self.width = int(self.vid.get(cv2.CAP_PROP_FRAME_WIDTH))
            self.height = int(self.vid.get(cv2.CAP_PROP_FRAME_HEIGHT))
            self.worker = threading.Thread(target = frame_provider.read_file, args = (self, ))
            
        elif mode == 'cam':
            import gxipy as gx 

            self.device_manager = gx.DeviceManager()
            dev_num, dev_info_list = self.device_manager.update_device_list()
            if dev_num == 0 or len(dev_info_list) == 0:
                print('没有找到可用的GigE设备。')
                raise IOError('没有找到可用的GigE设备。')
                
            print("找到{}台设备:{}。".format(dev_num, dev_info_list))

            if cam_ip is None or cam_ip == "": 
                cam_ip = dev_info_list[0].get("ip")
                print("未指定IP,使用: {}".format(dev_info_list[0].get("ip")))
            
            print('打开网络相机 (IP: {}), 进程PID: {}.'.format(cam_ip, os.getpid()))
            self.cam = self.device_manager.open_device_by_ip(cam_ip)
            
            self.cam.TriggerMode.set(gx.GxSwitchEntry.OFF)

            # Set the cam Height and Width. 
            self.cam.Width.set(width)
            self.cam.Height.set(height)

            # Set exposure
            if auto_expose:
                self.cam.ExposureAuto.set(1)
            else:
                self.cam.ExposureAuto.set(0)
                self.cam.ExposureTime.set(200.0)

            # set gain. 
            self.cam.Gain.set(10.0)

            # Start data acquisition. 
            self.cam.stream_on()

            self.width = width
            self.height = height
            self.worker = threading.Thread(target = frame_provider.read_cam, args = (self, ))

        else: 
            raise ValueError('模式设置错误, mode: '.format(mode))

        if record:
            if out_file is None:
                out_file = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + '.mp4'
            
            video_FourCC = cv2.VideoWriter_fourcc("m", "p", "4", "v")
            output_res = (self.width, self.height)
            self.out = cv2.VideoWriter(out_file, video_FourCC, 50, output_res)
            if self.out.isOpened():
                print('输出记录文件: {}. '.format(out_file))
            else:
                print('输出记录文件打开失败: {}. '.format(out_file))
                return
        else:
            self.out = None 

        self.mode = mode 
        self.lock = threading.Lock()
        self.frame = None
        self.fps = 0
Ejemplo n.º 17
0
def main():

    Width_set = 640  # 设置分辨率宽
    Height_set = 480  # 设置分辨率高
    framerate_set = 80  # 设置帧率
    num = 500  # 采集帧率次数(为调试用,可把后边的图像采集设置成while循环,进行无限制循环采集)

    #打印
    print("")
    print("###############################################################")
    print("               连续获取彩色图像并显示获取的图像.")
    print("###############################################################")
    print("")
    print("摄像机初始化......")
    print("")

    #创建设备
    device_manager = gx.DeviceManager()  # 创建设备对象
    dev_num, dev_info_list = device_manager.update_device_list(
    )  #枚举设备,即枚举所有可用的设备
    if dev_num is 0:
        print("Number of enumerated devices is 0")
        return
    else:
        print("")
        print("**********************************************************")
        print("创建设备成功,设备号为:%d" % dev_num)

    #通过设备序列号打开一个设备
    cam = device_manager.open_device_by_sn(dev_info_list[0].get("sn"))

    #如果是黑白相机
    if cam.PixelColorFilter.is_implemented(
    ) is False:  # is_implemented判断枚举型属性参数是否已实现
        print("该示例不支持黑白相机.")
        cam.close_device()
        return
    else:
        print("")
        print("**********************************************************")
        print("打开彩色摄像机成功,SN号为:%s" % dev_info_list[0].get("sn"))

    #设置宽和高
    cam.Width.set(Width_set)
    cam.Height.set(Height_set)
    """
    #设置曝光
    cam.ExposureTime.set(10000.0) # 设置当前曝光值范围内任意值
    
    #设置增益
    cam.Gain.set(10.0)
   
    #设置图像增强参数
    if cam.GammaParam.is_readable():
        gamma_value = cam.GammaParam.get()
        gamma_lut = gx.Utility.get_gamma_lut(gamma_value)
    else:
        gamma_lut = None
    if cam.ContrastParam.is_readable():
        contrast_value = cam.ContrastParam.get()
        contrast_lut = gx.Utility.get_contrast_lut(contrast_value)
    else:
        contrast_lut = None
    color_correction_param = cam.ColorCorrectionParam.get()
    """

    #设置连续采集
    #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):
        raw_image = cam.data_stream[0].get_image()  # 打开第0通道数据流
        if raw_image is None:
            print("获取彩色原始图像失败.")
            continue

        rgb_image = raw_image.convert("RGB")  # 从彩色原始图像获取RGB图像
        if rgb_image is None:
            continue

        #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:
            continue

        img = Image.fromarray(numpy_image, 'RGB')  # 展示获取的图像
        #img.show()
        mtime = datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')

        img.save(r"D:\image\\" + 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()
Ejemplo n.º 18
0
if __name__=='__main__':
    #1-blue 2-red
    ENEMY_COLOR=1
    
    detecting   = Value(c_bool, True)
    initracker  = Value(c_bool, False)
    tracking    = Value(c_bool, False)
    flag        = Value('I', 0)  # num of tracking frames
    direction   = Value('I', 7)  # default direction is tracking
    # ArmorInfo varibles shared by all process
    # xmin,ymin,width,height
    boundingbox = Array('I', [0, 0, 0, 0]) # unsigned int bbox

    yolov5_wrapper = YoLov5TRT("build/yolov5s.engine",detecting, tracking, initracker, 
                        boundingbox, direction, image_in, ENEMY_COLOR)
    device_manager = gx.DeviceManager() 
    dev_num, dev_info_list = device_manager.update_device_list()
    if dev_num == 0:
        sys.exit(1)
    str_sn = dev_info_list[0].get("sn")
    cam = device_manager.open_device_by_sn(str_sn)
    
    cam.stream_on()
    while(1):
        cam.data_stream[0].flush_queue()
        t1 = time.clock()
        raw1_image = cam.data_stream[0].get_image(timeout=10000000)
        rgb1_image = raw1_image.convert("RGB")
        numpy1_image = rgb1_image.get_numpy_array()
        image_raw = cv2.cvtColor(numpy1_image, cv2.COLOR_RGB2BGR)
        yolov5_wrapper.infer(image_raw)
Ejemplo n.º 19
0
def main():
    # print the demo information
    print("")
    print("-------------------------------------------------------------")
    print("Sample to show how to acquire mono or color image by callback "
          "and show acquired image.")
    print("-------------------------------------------------------------")
    print("")
    print("Initializing......")
    print("")

    # create a device manager
    device_manager = gx.DeviceManager()
    dev_num, dev_info_list = device_manager.update_device_list()
    if dev_num is 0:
        print("Number of enumerated devices is 0")
        return

    # open the first device
    cam = device_manager.open_device_by_index(1)

    # set exposure
    cam.ExposureTime.set(10000)

    if dev_info_list[0].get("device_class") == gx.GxDeviceClassList.USB2:
        # set trigger mode
        cam.TriggerMode.set(gx.GxSwitchEntry.ON)
    else:
        # set trigger mode and trigger source
        cam.TriggerMode.set(gx.GxSwitchEntry.ON)
        cam.TriggerSource.set(gx.GxTriggerSourceEntry.SOFTWARE)

    # get data stream
    data_stream = cam.data_stream[0]

    # Register capture callback (Notice: Linux USB2 SDK does not support register_capture_callback)
    if cam.PixelColorFilter.is_implemented() is True:
        data_stream.register_capture_callback(capture_callback_color)
    else:
        data_stream.register_capture_callback(capture_callback_mono)

    # start data acquisition
    cam.stream_on()

    print('<Start acquisition>')
    time.sleep(0.1)

    # Send trigger command
    cam.TriggerSoftware.send_command()

    # Waiting callback
    time.sleep(1)

    # stop acquisition
    cam.stream_off()
    
    print('<Stop acquisition>')

    # Unregister capture callback
    data_stream.unregister_capture_callback()

    # close device
    cam.close_device()