<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;"># -*- coding:utf-8 -*-
# For Ground-based observation for LAMP rocket mission,
# this code conducts All-Sky imgaer QL analysis

import sys
import time
import zwoasi as asi
import numpy as np
from collections import deque
import matplotlib.pyplot as plt
from matplotlib import colors
#import threading
from scipy.interpolate import interp1d
from scipy import signal
from datetime import datetime, timezone, timedelta
import os
import cv2

__author__ = 'Naoshi Yagi'
__status__ = "production"
__version__ = '0.0.4'
__date__    = "17 December 2019"

UT = timezone(timedelta(hours=+0),'UT') # Set time zone to Universal Time

#--------------------------------------------------------------------------------------------------
# Command line parameters
#--------------------------------------------------------------------------------------------------

args=sys.argv
if (len(args) != 3) :
        print("")
        print("Print_Usage:")
        print("")
        print("  multi_zwo_asi.py  camera_id  exposure(ms)")
        print("")
        print("  ex)  python3  multi_zwo_asi.py  0  100")
        print("")
        sys.exit()

camera_id = int(args[1])
expo_time = int(args[2])

##############################################################
##       Boot and Initialaization of ASI camera             ##
##############################################################

# Path to the library of zwo asi camera
SDK_file=r'/home/psa-gnd/ASIStudio/lib/libASICamera2.so'

# Initialization of asi camera
try:
    print('Already initialized: %s'%init)
except NameError:
    asi.init(SDK_file)
    init=True
print('Cameras are initialized')

# Get the number of cameras available
num_cameras = asi.get_num_cameras()
if num_cameras == 0:
    print('No cameras found')
    sys.exit(0)

# List the cameras available
list_of_cameras = asi.list_cameras()
if num_cameras == 1:
    print('  Found one camera: %s' % list_of_cameras[0])
else:
    print('  Found %d cameras' % num_cameras)
    for i in range(num_cameras):
      print('    #%d: %s' % (i, list_of_cameras[i]))

# Choose which camera will be used
camera = asi.Camera(camera_id)
camera_info = camera.get_camera_property()
print('Going to use #%d: %s' % (camera_id, camera_info['Name']))

# Check the controlable parameters if you want
control_param_print=False #change this to True to check controlable parameters
if control_param_print:
    print('')
    print('camera info')
    print(camera_info)

    print('')
    print('Camera controls:')
    controls = camera.get_controls()
    for cn in sorted(controls.keys()):
        print('    %s:' % cn)
        for k in sorted(controls[cn].keys()):
            print('        %s: %s' % (k, repr(controls[cn][k])))

##############################################################
##          Checking the temperature of ASI camera          ##
##############################################################

camera.set_control_value(asi.ASI_TARGET_TEMP,-40)
camera.set_control_value(asi.ASI_COOLER_ON,1)
camera.set_control_value(asi.ASI_FAN_ON,1)
print('Checking the temperature of the sensor')
print(' (temperature is below -11.5, then capturing will start)')
while True:
     current_temp=camera.get_control_value(asi.ASI_TEMPERATURE)[0]
     time.sleep(1)
     print('\r Current temperature %s C' % str(current_temp/10.0),end="")
     if current_temp &lt; -110: break

print('Cooler ON/OFF status: %s' % str(camera.get_control_value(asi.ASI_COOLER_ON)[0]))
print('Cooler ON/OFF status: %s' % str(camera.get_control_value(asi.ASI_FAN_ON)[0]))

##############################################################
##         Setting parameters of image and camera           ##
##############################################################

# the following are for setting some parameters
width   = 3672 # the original vertical size of the sensor
height  = 3672
asi_bins= 4    # (max 4) this 4x4 binnig is efficient since ADC is 12bit and dataout put is always 16bit
width   = int(width/(asi_bins*8)) * 8  # this ROI shoud be multiples of (binning pix num) x 8,
height  = int(height/(asi_bins*8)) * 8 # i.e. with 4x4 binning, this should be (interger x 32)
print("capturing with ROI = (%d pix, %d pix), %d x %d pix/bin "%(width*asi_bins, height*asi_bins, asi_bins, asi_bins))

# Loop for gain and gamma
for gain_stng in range(0,451,50):
    for gamma_val in range(25,71,5):
#for gain_stng in range(0,401,100):
#    for gamma_val in range(30,71,10):

        camera.set_control_value(asi.ASI_GAIN,gain_stng) # Gain
        camera.set_control_value(asi.ASI_EXPOSURE,expo_time*1000) # Exposure time [us]
        camera.set_control_value(asi.ASI_GAMMA,gamma_val) # gamma=50 corresponds to linearity
        camera.set_roi(width=width,height=height,bins=asi_bins) # ROI and software bin
        camera.set_control_value(asi.ASI_BANDWIDTHOVERLOAD,95) # bandwidth of USB. 95 seems to be best
        camera.set_image_type(asi.ASI_IMG_RAW16) # Samplig at 16 [bit/pix]
        print('-----------------------------------------------------------------------')
        print('Gain: %s, Gamma: %s, Exposure: %s ms' % (str(camera.get_control_value(asi.ASI_GAIN)[0]),str(camera.get_control_value(asi.ASI_GAMMA)[0]),str(camera.get_control_value(asi.ASI_EXPOSURE)[0]/1000)))
        print('-----------------------------------------------------------------------')

##############################################################
##               Make Directory and log file                ##
##############################################################

        path = "/home/psa-gnd/data/C{0:02}/".format(camera_id)
        t0=datetime.now(UT) # current time
        ymd   = t0.strftime('%Y%m%d')
        hms   = t0.strftime('%H%M%S')
        gam   = str(gamma_val).zfill(3)
        exp   = str(expo_time).zfill(3)
        gan   = str(gain_stng).zfill(3)
        dir_n = path + ymd +"_"+exp+"_"+gan+"_"+gam
        os.makedirs(dir_n, exist_ok=True)

        img_raw=camera.capture()
        w,h=img_raw.shape # checking the shape of output images
        with open(dir_n + '/parameter.txt','w') as f:
            for k in sorted(camera.get_control_values().keys()):
                f.write('%s: %s\n' % ( k, str(camera.get_control_values()[k] ) ))
            f.write('Binning mode: %s\n'%asi_bins)
            f.write('Width: %d\n'%w)
            f.write('Height: %d\n'%h)

##############################################################
##                      Video capture                       ##
##############################################################
        
        cv2.namedWindow("Image data",cv2.WINDOW_NORMAL)
        cv2.resizeWindow("Image data",500,500)
        
        # start video mode
        camera.start_video_capture()
        fc = 0 #frame coutner
        while True:
            cap_time = datetime.now(UT)
            img_raw = camera.capture_video_frame( filename = dir_n + '/%s_no%d.tiff'%(cap_time.strftime('%Y-%m-%d_%H%M%S_%f'), fc ) )
            if fc % 10 == 0:
                 print("%s, Frame number %d, Temperature: %s" % (cap_time.strftime('%Y/%m/%d %H:%M:%S.%f'), fc, str(camera.get_control_value(asi.ASI_TEMPERATURE)[0])))
            cv2.imshow('Image data', cv2.flip(img_raw, 0))
            cv2.waitKey(1)
            fc+=1
            if fc == 100: break
        
        cv2.destroyAllWindows()
        camera.stop_exposure()

cv2.destroyAllWindows()
camera.set_control_value(asi.ASI_COOLER_ON,0)
camera.set_control_value(asi.ASI_FAN_ON,0)
camera.stop_exposure()
</pre></body></html>