예제 #1
0
 def _shut_down(self):
     try:
         self.cam.close()
         pvc.uninit_pvcam()
         return True
     except BaseException:
         return False
예제 #2
0
def main():
    # Initialize PVCAM and find the first available camera.
    pvc.init_pvcam()

    cam = [cam for cam in Camera.detect_camera()][0]
    cam.open()
    cam.speed_table_index = 0
    cam.exp_mode = 'Software Trigger Edge'

    # Start a thread for executing the trigger
    t1 = TriggerThreadRun(cam)
    t1.start()

    # Collect frames in live mode
    cam.start_live()
    framesReceived = collectFrames(cam)
    cam.finish()
    print('Received live frames: ' + str(framesReceived) + '\n')

    # Collect frames in sequence mode
    cam.start_seq(num_frames=NUM_FRAMES)
    framesReceived = collectFrames(cam)
    cam.finish()
    print('Received seq frames: ' + str(framesReceived) + '\n')

    t1.stop()
    cam.close()
    pvc.uninit_pvcam()

    print('Done')
예제 #3
0
def main():
    # Initialize PVCAM and find the first available camera.
    pvc.init_pvcam()

    cam = [cam for cam in Camera.detect_camera()][0]
    cam.open()

    cam.start_seq(exp_time=EXPOSE_TIME_ms, num_frames=NUM_FRAMES)

    # Wait for 3 frames to be captured. Frames take a slightly longer than expose time, so wait a little extra time
    time.sleep(3 * EXPOSE_TIME_ms * 1e-3 + 0.1)

    cnt = 0
    while cnt < NUM_FRAMES:
        frame, fps, frame_count = cam.poll_frame(oldestFrame=False)
        printFrameDetails(frame, fps, frame_count, 'newest')

        frame, fps, frame_count = cam.poll_frame()
        printFrameDetails(frame, fps, frame_count, 'oldest')

        cnt += 1

    cam.finish()
    cam.close()
    pvc.uninit_pvcam()

    print('\nTotal frames: {}'.format(cnt))
예제 #4
0
def main():
    pvc.init_pvcam()
    cam = next(Camera.detect_camera())
    cam.open()
    cam.meta_data_enabled = True
    cam.roi = (0, 1000, 0, 1000)

    num_frames = 1
    cnt = 0

    cam.start_seq(exp_time=20, num_frames=num_frames)
    while cnt < num_frames:
        frame, fps, frame_count = cam.poll_frame()

        low = np.amin(frame['pixel_data'])
        high = np.amax(frame['pixel_data'])
        average = np.average(frame['pixel_data'])

        print(
            'Min:{}\tMax:{}\tAverage:{:.0f}\tFrame Rate: {:.1f}\tFrame Count: {:.0f}\n'
            .format(low, high, average, fps, frame_count))
        cnt += 1

        time.sleep(0.05)

    cam.finish()
    cam.close()
    pvc.uninit_pvcam()

    print('Total frames: {}\n'.format(cnt))
def main():
    pvc.init_pvcam()
    cam = next(Camera.detect_camera())
    cam.open()

    frame = cam.get_frame(exp_time=20).reshape(cam.sensor_size[::-1])
    plt.imshow(frame, cmap="gray")
    plt.show()
    cam.close()
    pvc.uninit_pvcam()
예제 #6
0
def close_cam(cam):
    ''' Closes the PVCAM instance
    args:
        - camera instance 
    '''
    try:
        cam.close()
        pvc.uninit_pvcam()
    except:
        print('Could not close Camera')
예제 #7
0
def main():
    # Initialize PVCAM and find the first available camera.
    pvc.init_pvcam()
    cam = [cam for cam in Camera.detect_camera()][0]
    cam.open()
    cam.speed_table_index = 0
    for i in range(5):
        frame = cam.get_frame(exp_time=20)
        print("First five pixels of frame: {}, {}, {}, {}, {}".format(
            *frame[:5]))
    cam.close()
    pvc.uninit_pvcam()
예제 #8
0
def main():
    pvc.init_pvcam()
    cam = next(Camera.detect_camera())
    cam.open()

    NUM_FRAMES = 10
    cnt = 0

    cam.start_seq(exp_time=20, num_frames=NUM_FRAMES)
    while cnt < NUM_FRAMES:
        frame, fps, frame_count = cam.poll_frame()

        low = np.amin(frame['pixel_data'])
        high = np.amax(frame['pixel_data'])
        average = np.average(frame['pixel_data'])

        print(
            'Min:{}\tMax:{}\tAverage:{:.0f}\tFrame Rate: {:.1f}\tFrame Count: {:.0f}\n'
            .format(low, high, average, fps, frame_count))
        cnt += 1

        time.sleep(0.05)

    cam.finish()

    # Test basic sequence methods
    frames = cam.get_sequence(NUM_FRAMES)
    for frame in frames:
        low = np.amin(frame)
        high = np.amax(frame)
        average = np.average(frame)

        print('Min:{}\tMax:{}\tAverage:{:.0f}\tFrame Count: {:.0f}\n'.format(
            low, high, average, cnt))
        cnt += 1

    time_list = [i * 10 for i in range(1, NUM_FRAMES + 1)]
    frames = cam.get_vtm_sequence(time_list, constants.EXP_RES_ONE_MILLISEC,
                                  NUM_FRAMES)
    for frame in frames:
        low = np.amin(frame)
        high = np.amax(frame)
        average = np.average(frame)

        print('Min:{}\tMax:{}\tAverage:{:.0f}\tFrame Count: {:.0f}\n'.format(
            low, high, average, cnt))
        cnt += 1

    cam.close()
    pvc.uninit_pvcam()

    print('Total frames: {}\n'.format(cnt))
예제 #9
0
def main():
    pvc.init_pvcam()
    cam = next(Camera.detect_camera())
    cam.open()

    cam.meta_data_enabled = True

    cam.set_roi(0, 0, 250, 250)
    cam.set_roi(300, 100, 400, 900)
    cam.set_roi(750, 300, 200, 200)

    NUM_FRAMES = 1

    cnt = 0

    cam.start_seq(exp_time=20, num_frames=NUM_FRAMES)
    while cnt < NUM_FRAMES:
        frame, fps, frame_count = cam.poll_frame()

        num_rois = len(frame['pixel_data'])
        for roi_index in range(num_rois):
            low = np.amin(frame['pixel_data'][roi_index])
            high = np.amax(frame['pixel_data'][roi_index])
            average = np.average(frame['pixel_data'][roi_index])

            s1 = frame['meta_data']['roi_headers'][roi_index]['roi']['s1']
            s2 = frame['meta_data']['roi_headers'][roi_index]['roi']['s2']
            p1 = frame['meta_data']['roi_headers'][roi_index]['roi']['p1']
            p2 = frame['meta_data']['roi_headers'][roi_index]['roi']['p2']
            print('ROI:{:2} ({:4}, {:4}) ({:4}, {:4})\tMin:{}\tMax:{}\tAverage:{:.0f}\tFrame Rate: {:.1f}\tFrame Count: {:.0f}'.format(roi_index, s1, p1, s2, p2, low, high, average, fps, frame_count))

            alpha = 2.0  # Contrast control (1.0-3.0)
            beta = 10  # Brightness control (0-100)
            img = cv2.convertScaleAbs(frame['pixel_data'][roi_index], alpha=alpha, beta=beta)

            window_name = 'Region: {}'.format(roi_index)
            cv2.imshow(window_name, img)
            cv2.moveWindow(window_name, s1, p1)

        cnt += 1

        cv2.waitKey(0)

    cam.finish()
    cam.close()
    pvc.uninit_pvcam()

    print('Total frames: {}\n'.format(cnt))
예제 #10
0
파일: test_camera.py 프로젝트: dwaithe/amca
def main():
    # Initialize PVCAM and find the first available camera.
    pvc.init_pvcam()

    cam = [cam for cam in Camera.detect_camera()][0]
    cam.open()
    cam.gain = 1
    cam.exp_mode = "Timed"
    cam.binning = 2  #Binning to set camera to collect at
    #cam.update_mode()
    cam.exp_out_mode = 0
    #cam.speed_table_index = 0
    #With the CoolLED pE-300 Ultra in sequence mode, this will cycle through the 3 lamps.
    t0 = time.time()
    frame1 = cam.get_frame(exp_time=50)  #Exposure channel 1
    frame2 = cam.get_frame(exp_time=10)  #Exposure channel 2
    frame3 = cam.get_frame(exp_time=300)  #Exposure channel 3
    im_stk = np.zeros((3, frame1.shape[0], frame2.shape[1]))
    im_stk[0, :, :] = frame1
    im_stk[1, :, :] = frame2
    im_stk[2, :, :] = frame3

    out_file_path = "../../../Desktop/2020_11_13_training_imgs/"
    from os import listdir
    from os.path import isfile, join
    onlyfiles = [
        f for f in listdir(out_file_path) if isfile(join(out_file_path, f))
    ]
    leng = onlyfiles.__len__()
    lenstr = str(leng + 1).zfill(5)

    tifffile.imsave(out_file_path + 'pos' + lenstr + '.tif',
                    im_stk.astype(np.uint16),
                    imagej=True)

    t1 = time.time()
    print(np.round(t1 - t0, 3), "s to acquire")
    cam.close()
    pvc.uninit_pvcam()
    f, axes = plt.subplots(3, 2)
    axes[0, 0].imshow(frame1, cmap=plt.get_cmap('Blue1'))
    axes[0, 1].hist(frame1.flatten(), bins=np.arange(0, 65535, 1000))
    axes[1, 0].imshow(frame2, cmap=plt.get_cmap('Green1'))
    axes[1, 1].hist(frame2.flatten(), bins=np.arange(0, 65535, 1000))
    axes[2, 0].imshow(frame3, cmap=plt.get_cmap('Red1'))
    axes[2, 1].hist(frame3.flatten(), bins=np.arange(0, 65535, 1000))
    plt.show()
예제 #11
0
def main():
    pvc.init_pvcam()
    cam = next(Camera.detect_camera())
    cam.open()
    cam.start_live(exp_time=20)
    cnt = 0
    tot = 0
    t1 = time.time()
    start = time.time()
    width = 800
    height = int(cam.sensor_size[1] * width / cam.sensor_size[0])
    dim = (width, height)
    fps = 0

    while True:
        frame, fps, frame_count = cam.poll_frame()
        frame['pixel_data'] = cv2.resize(frame['pixel_data'],
                                         dim,
                                         interpolation=cv2.INTER_AREA)
        cv2.imshow('Live Mode', frame['pixel_data'])

        low = np.amin(frame['pixel_data'])
        high = np.amax(frame['pixel_data'])
        average = np.average(frame['pixel_data'])

        if cnt == 10:
            t1 = time.time() - t1
            fps = 10 / t1
            t1 = time.time()
            cnt = 0
        if cv2.waitKey(10) == 27:
            break
        print('Min:{}\tMax:{}\tAverage:{:.0f}\tFrame Rate: {:.1f}\n'.format(
            low, high, average, fps))
        cnt += 1
        tot += 1

    cam.finish()
    cam.close()
    pvc.uninit_pvcam()

    print('Total frames: {}\nAverage fps: {}\n'.format(
        tot, (tot / (time.time() - start))))
예제 #12
0
    print("Param scan line time is automatically now {0}".format(
        cam.get_param(const.PARAM_SCAN_LINE_TIME, const.ATTR_CURRENT)))
    print("Param line delay is automatically now {0}".format(
        cam.get_param(const.PARAM_SCAN_LINE_DELAY, const.ATTR_CURRENT)))

    # Get frames and time to sequence
    start = time.time()
    frames = cam.get_sequence(num_frames=test_num_frames,
                              exp_time=test_exp_time)
    end = time.time()

    # Since numpy's mean can be inaccurate in single precision, computing in float64 instead, which is more accurate
    sw_mean = np.mean(frames, dtype=np.float64)
    sw_seq_time = end - start

    print(
        "First five rows of frame: {}, {}, {}, {}, {}".format(*frames[0][:5]))
    print("Mean = {0} ADU".format(sw_mean))
    print("Time to sequence = {0}".format(sw_seq_time))

    assert sw_seq_time > auto_seq_time_hdr_1, "Auto Mode sequence time was greater than Scan Width sequence time (HDRG1)"

else:
    print("PSM isn't available")

cam.close()
pvc.uninit_pvcam()

print('Finished test')
예제 #13
0
def uninitPVCAM():
    """
    Closes the library.
    """
    pvc.uninit_pvcam()
예제 #14
0
 def close(self):
     iself.cam.close()
     pvc.uninit_pvcam()
예제 #15
0
def main():
    pvc.init_pvcam()
    cam = next(Camera.detect_camera())
    cam.open()
    cam.meta_data_enabled = True
    cam.set_roi(0, 0, WIDTH, HEIGHT)
    cam.start_live(exp_time=100,
                   buffer_frame_count=BUFFER_FRAME_COUNT,
                   stream_to_disk_path=FRAME_DATA_PATH)

    # Data is streamed to disk in a C++ call-back function invoked directly by PVCAM. To not overburden the system,
    # only poll for frames in python at a slow rate, then exit when the frame count indicates all frames have been
    # written to disk
    while True:
        frame, fps, frame_count = cam.poll_frame()

        if frame_count >= NUM_FRAMES:
            low = np.amin(frame['pixel_data'])
            high = np.amax(frame['pixel_data'])
            average = np.average(frame['pixel_data'])
            print(
                'Min:{}\tMax:{}\tAverage:{:.0f}\tFrame Count:{:.0f} Frame Rate: {:.1f}'
                .format(low, high, average, frame_count, fps))
            break

        time.sleep(1)

    cam.finish()

    imageFormat = cam.get_param(const.PARAM_IMAGE_FORMAT)
    if imageFormat == const.PL_IMAGE_FORMAT_MONO8:
        BYTES_PER_PIXEL = 1
    else:
        BYTES_PER_PIXEL = 2

    cam.close()
    pvc.uninit_pvcam()

    # Read out meta data from stored frames
    FRAME_ALIGNMENT = 0  # Typically 0. 32 for Kinetix PCIe
    FRAME_BUFFER_ALIGNMENT = 4096
    META_DATA_FRAME_HEADER_SIZE = 48
    META_DATA_ROI_SIZE = 32
    META_DATA_SIZE = META_DATA_FRAME_HEADER_SIZE + META_DATA_ROI_SIZE
    pixelsPerFrame = WIDTH * HEIGHT
    bytesPerFrameUnpadded = pixelsPerFrame * BYTES_PER_PIXEL + META_DATA_SIZE
    framePad = 0 if FRAME_ALIGNMENT == 0 else FRAME_ALIGNMENT - (
        bytesPerFrameUnpadded % FRAME_ALIGNMENT)
    bytesPerFrame = bytesPerFrameUnpadded + framePad
    frameBufferAlignmentPad = FRAME_BUFFER_ALIGNMENT - (
        (BUFFER_FRAME_COUNT * bytesPerFrame) % FRAME_BUFFER_ALIGNMENT)

    with open(FRAME_DATA_PATH, "rb") as f:

        badMetaDataCount = 0
        for frame_index in range(NUM_FRAMES):
            frame_number = frame_index + 1

            # Read frame number from meta data header
            # Every time the circular buffer wraps around, bytes are padded into the file. This is a result of needing to
            # write data in chunks that are multiples of the alignment boundary.
            frameBufferPad = int(
                frame_index / BUFFER_FRAME_COUNT) * frameBufferAlignmentPad

            FRAME_NUMBER_OFFSET = 5
            filePos = frame_index * bytesPerFrame + FRAME_NUMBER_OFFSET + frameBufferPad
            f.seek(filePos, 0)
            frameNumberBytes = f.read(4)

            frame_number_meta_data = int.from_bytes(frameNumberBytes, 'little')

            if frame_number != frame_number_meta_data:
                badMetaDataCount += 1
                print('Expected: ' + str(frame_number) + ' Observed: ' +
                      str(frame_number_meta_data))

    print('Verified ' + str(NUM_FRAMES) + ' frames:')
    print('  Meta data errors: ' + str(badMetaDataCount))

    if badMetaDataCount > 0:
        print('\nMeta data error troubleshooting:')
        print('  1. Verify FRAME_ALIGNMENT for camera and interface')
        print('  2. Increase exposure time')
예제 #16
0
def main():
    pvc.init_pvcam()
    cam = next(Camera.detect_camera())
    cam.open()

    cnt = 0

    # Check status from sequence collect
    cam.start_seq(exp_time=1000, num_frames=2)

    acquisitionInProgress = True
    while acquisitionInProgress:

        frameStatus = cam.check_frame_status()
        print('Seq frame status: ' + frameStatus)

        if frameStatus == 'READOUT_NOT_ACTIVE' or frameStatus == 'FRAME_AVAILABLE' or frameStatus == 'READOUT_COMPLETE' or frameStatus == 'READOUT_FAILED':
            acquisitionInProgress = False

        if acquisitionInProgress:
            time.sleep(0.05)

    if frameStatus != 'READOUT_FAILED':
        frame, fps, frame_count = cam.poll_frame()

        low = np.amin(frame['pixel_data'])
        high = np.amax(frame['pixel_data'])
        average = np.average(frame['pixel_data'])

        print(
            'Min:{}\tMax:{}\tAverage:{:.0f}\tFrame Rate: {:.1f}\tFrame Count: {:.0f}'
            .format(low, high, average, fps, frame_count))

    cam.finish()

    frameStatus = cam.check_frame_status()
    print('Seq post-acquisition frame status: ' + frameStatus + '\n')

    # Check status from live collect. Status will only report FRAME_AVAILABLE between acquisitions, so an indeterminate number of frames are needed
    # before we catch the FRAME_AVAILABLE status
    cam.start_live(exp_time=10)

    acquisitionInProgress = True
    while acquisitionInProgress:

        frameStatus = cam.check_frame_status()
        print('Live frame status: ' + frameStatus)

        if frameStatus == 'READOUT_NOT_ACTIVE' or frameStatus == 'FRAME_AVAILABLE' or frameStatus == 'READOUT_FAILED':
            acquisitionInProgress = False

        if acquisitionInProgress:
            time.sleep(0.05)

    if frameStatus != 'READOUT_FAILED':
        frame, fps, frame_count = cam.poll_frame()

        low = np.amin(frame['pixel_data'])
        high = np.amax(frame['pixel_data'])
        average = np.average(frame['pixel_data'])

        print(
            'Min:{}\tMax:{}\tAverage:{:.0f}\tFrame Rate: {:.1f}\tFrame Count: {:.0f}'
            .format(low, high, average, fps, frame_count))

    cam.finish()

    frameStatus = cam.check_frame_status()
    print('Live post-acquisition frame status: ' + frameStatus)

    cam.close()

    pvc.uninit_pvcam()
예제 #17
0
 def tearDown(self):
     # if self.test_cam.is_open():
     #     self.test_cam.close()
     pvc.uninit_pvcam()