<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  frame_rate")
        print("")
        print("  ex)  python3  multi_zwo_asi.py  0  10")
        print("")
        sys.exit()

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

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

#path to the library od zwo asi camera
#SDK_file=r'C:/Users/admin/Desktop/ASI_Windows_SDK_V1.14.1119/ASI SDK/lib/x64/ASICamera2.dll'
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])))

# Setting of frame rate
if int(framerate) == 10 : #10Hz sampling
    Exposure_time= 100 #[ms]
#    camera.set_control_value(asi.ASI_GAIN,400) # Gain
    camera.set_control_value(asi.ASI_GAIN,100) # Gain
    freq=10.0
    print('10Hz sampling')
    
elif int(framerate) == 1 : #1Hz sampling
    Exposure_time= 1000 #[ms]
    camera.set_control_value(asi.ASI_GAIN,200) # Gain
    print('1Hz sampling')
    freq=1.0
    
elif int(framerate) == 2 : #10s sampling
    Exposure_time= 10000 #[ms]
    camera.set_control_value(asi.ASI_GAIN,250) # Gain
    freq=1.0
    print('10s sampling')

else:
    print('You need to set the Exposure_time')
    sys.exit(0)


##############################################################
##          setting some parameters of ASI camera           ##
##############################################################

# the following are for setting some parameters
asi_bin_only=True #use only zwoasi library bins. False leads to binning with numpy library
if asi_bin_only:
    width   = 3672 #the vertical size
    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]), %dx%d[pix/bin] "%(width*asi_bins, height*asi_bins, asi_bins, asi_bins))

else:
    width  = 3672 # with numpy bin, any ROI can be binned.
    height = 3672 # So here ROI is chosen to be the max vaule to be square image
    bin_num= 4   # this corresponds to n, where nxn binning is to be conducted
    asi_bins= 1 # not using zwoasi library bins

    #since ROI(widht,height) should be maltixples of bin_num
    width   = int(width/bin_num) * bin_num
    height  = int(height/bin_num) * bin_num
    b_width = int(width/bin_num)  #width of binned image
    b_height= int(height/bin_num) #height of binned image
    print("capturing with ROI=(%d [pix], %d [pix]), %dx%d[pix/bin] "%(width, height, bin_num, bin_num))

camera.set_control_value(asi.ASI_EXPOSURE, 99900) #Exposure time[us]
#camera.set_control_value(asi.ASI_EXPOSURE, Exposure_time*1000) #Exposure time[us]
camera.set_control_value(asi.ASI_GAMMA, 50) # gammma/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]

##############################################################
##         Checking the size of output images               ##
##############################################################
def save_control_values(filename, settings):
    filename += '.txt'
    with open(filename, 'w') as f:
        for k in sorted(settings.keys()):
            f.write('%s: %s\n' % (k, str(settings[k])))
    print('Camera settings saved to %s' % filename)
    
print('Capturing a single 16-bit mono image')
filename = 'image_mono16.tiff'
camera.set_image_type(asi.ASI_IMG_RAW16)
img_raw=camera.capture(filename=filename)
print('Saved to %s' % filename)
save_control_values(filename, camera.get_control_values())    
# start video mode
#camera.start_video_capture()

# capture one frame for initiazing figure
#img_raw=camera.capture_video_frame()
t0=datetime.now(UT) # current time when capturing an image for ploting
if not asi_bin_only: #in this case, software binning by numpy library should be added
    img_raw = img_raw.reshape(b_width,bin_num,b_height,bin_num).sum(3).sum(1) #binning
    img_raw = (img_raw/16).astype('u4') #convert output values to 4byte unsigned interger

w,h=img_raw.shape # checking the shape of output images

##############################################################
##               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')
dir_n = path + ymd
os.makedirs(dir_n, exist_ok=True)

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                       ##
##############################################################
fc = 0 #frame coutner

#cv2.namedWindow("Image data",cv2.WINDOW_NORMAL)
#cv2.resizeWindow("Image data",500,500)

# start video mode
camera.start_video_capture()
list_timelog = []
try:
    while True:
        cap_time = datetime.now(UT)
        list_timelog.append(cap_time.strftime('%Y-%m-%d_%H%M%S_%f'))
        img_raw = camera.capture_video_frame( filename = dir_n + '/%s_no%d.tiff'%(cap_time.strftime('%Y-%m-%d_%H%M%S_%f'), fc ) ) #capture an image data
        sec=cap_time.second
        if fc % 100 == 0: print("%s, Frame number %d"%(cap_time.strftime('%Y/%m/%d %H:%M:%S.%f'), fc))
#        print("\r"+"%s, Frame number %d"%(cap_time.strftime('%Y/%m/%d %H:%M:%S.%f'), fc) ,end="")
#        cv2.imshow('Image data', cv2.flip(img_raw, 0))
#        cv2.waitKey(1)

#        refresh()
#        threading.Thread(target=analysis).start() # using a multi thread, here conducting anaylsis function

        fc+=1
#        if plot_ready:
#            plt.pause(0.000001)
#            plot_ready = False

except KeyboardInterrupt:
    print('\nstop capturing.')
    
    with open(dir_n+'/timelog.txt', 'w') as fout:
        for time in list_timelog:
            fout.write(time + '\n')
        
    cv2.destroyAllWindows()
    camera.stop_exposure()
</pre></body></html>