def __init__(self): config = yaml.safe_load(open('solar_config.yml', 'r')) self.sio = socketio.Client() self.sio.connect(config['socketServer']) try: asi.init('./camera_software/lib/mac/libASICamera2.dylib') except: pass num_cameras = asi.get_num_cameras() if num_cameras == 0: print('No cameras found') sys.exit(0) self.camera = asi.Camera(0) self.camera_info = self.camera.get_camera_property() self.controls = self.camera.get_controls() self.camera.set_control_value(asi.ASI_BANDWIDTHOVERLOAD, self.camera.get_controls()['BandWidth']['MinValue']) self.camera.disable_dark_subtract() self.camera.set_control_value(asi.ASI_GAIN, 50) self.camera.set_control_value(asi.ASI_EXPOSURE, 800) self.camera.set_control_value(asi.ASI_GAIN, 100) self.camera.set_control_value(asi.ASI_EXPOSURE, 1000) self.camera.set_control_value(asi.ASI_WB_B, 99) self.camera.set_control_value(asi.ASI_WB_R, 75) self.camera.set_control_value(asi.ASI_GAMMA, 50) self.camera.set_control_value(asi.ASI_BRIGHTNESS, 50) self.camera.set_control_value(asi.ASI_FLIP, 0)
def init_cam(): asi.init(".\\ASICamera2.dll") num_cameras = asi.get_num_cameras() if num_cameras == 0: print('No cameras found') sys.exit(0) cameras_found = asi.list_cameras() # Models names of the connected cameras camera_id = 0 camera = asi.Camera(camera_id) print("found camera") camera.disable_dark_subtract() camera.set_control_value(asi.ASI_BANDWIDTHOVERLOAD, 40) camera.set_control_value(asi.ASI_GAIN, 20) camera.set_control_value(asi.ASI_EXPOSURE, int(0.00001 * 1000000)) camera.set_control_value(asi.ASI_GAMMA, 50) camera.set_control_value(asi.ASI_BRIGHTNESS, 85) camera.set_control_value(asi.ASI_FLIP, 0) camera.set_control_value(asi.ASI_FLIP, 0) camera.set_control_value(asi.ASI_HIGH_SPEED_MODE, 0) camera.set_control_value(asi.ASI_TARGET_TEMP, -14) camera.set_control_value(asi.ASI_COOLER_ON, 1) camera.set_control_value(asi.ASI_HARDWARE_BIN, 1) camera.set_roi(bins=3) camera.set_image_type(asi.ASI_IMG_RAW16) print("ready") return camera
def __init__(self,config, base =''): self.base_directory = base # load the SDK library asi.init(self.base_directory + "\dependencies\ASICamera2.dll") # initialize the camera self.camera = asi.Camera(0) # set 16 bit integer image type self.camera.set_image_type(asi.ASI_IMG_RAW16) # set gain for maximum dynamic range self.camera.set_control_value(asi.ASI_GAIN, 0) if socket.gethostname() == 'minerva19-01': self.xsize = 3096 self.ysize = 2080 else: self.xsize=1936 self.ysize=1216 self.guideimagelastupdate = datetime.datetime.utcnow() self.guidestarx = np.nan self.guidestary = np.nan self.x1 = 1 self.x2 = self.xsize self.y1 = 1 self.y2 = self.ysize self.imageReady = False # make it full frame self.camera.set_roi(start_x=0, start_y=0, width=self.xsize, height=self.ysize) self.img = np.asarray([])
def initialize(): # Initialize the ASI camera library and confirm we have at least one ASI camera connected: # # Note that this application will always pick the first camera - fine for me because I will only have one camera connected but could be an issue if that is not the case for you. If you need support for more than one ASI camera, edit the code below accordingly. global camera # Hard coded library location as fallback: #TODO: Generalize this so that library does not need to be hard coded ASI_LIBRARY = "/usr/local/lib/libASICamera2.so" asi.init(ASI_LIBRARY) num_cameras = asi.get_num_cameras() if num_cameras == 0: print('No cameras found') sys.exit(0) else: cameras_found = asi.list_cameras() print('Found %d cameras' % num_cameras) for n in range(num_cameras): print(' %d: %s' % (n, cameras_found[n])) camera_id = 0 print('Using #%d: %s' % (camera_id, cameras_found[camera_id])) # Setup Camera: camera = asi.Camera(camera_id) return camera
def __init__(self, config): if zwoasi.zwolib is None: # Must initialise the library if config.has_option('camera', 'sdk'): sdk_filename = config.get('camera', 'sdk') else: # Hope the user has set LD_LIBRARY_PATH or similar.. sdk_filename = None zwoasi.init(sdk_filename) num_cameras = zwoasi.get_num_cameras() if num_cameras == 0: raise Exception('no camera present') if config.has_option('camera', 'model'): id_ = config.get('camera', 'model') try: # Assume it is an integer id_ = int(id_) except ValueError: # No it wasn't, must be the model name then pass else: id_ = 0 self.camera = zwoasi.Camera(id_) self.config = config self.capture_image_lock = threading.Lock()
def __init__(self, zwo_asi_lib): self.zwo_asi_lib = zwo_asi_lib if zwo_asi_lib: asi.init(zwo_asi_lib) else: print( 'The filename of the SDK library is required set ZWO_ASI_LIB environment variable with the filename' ) sys.exit(1)
def open(self): """Open module.""" BaseCamera.open(self) # init driver asi.init(self._sdk_path) # get number of cameras num_cameras = asi.get_num_cameras() if num_cameras == 0: raise ValueError('No cameras found') # get ID of camera # index() raises ValueError, if camera could not be found cameras_found = asi.list_cameras() camera_id = cameras_found.index(self._camera_name) # open driver self._camera = asi.Camera(camera_id) self._camera_info = self._camera.get_camera_property() log.info('Camera info:') for key, val in self._camera_info.items(): log.info(' - %s: %s', key, val) # Set some sensible defaults. They will need adjusting depending upon # the sensitivity, lens and lighting conditions used. self._camera.disable_dark_subtract() self._camera.set_control_value(asi.ASI_GAIN, 150) self._camera.set_control_value(asi.ASI_WB_B, 99) self._camera.set_control_value(asi.ASI_WB_R, 75) self._camera.set_control_value(asi.ASI_GAMMA, 50) self._camera.set_control_value(asi.ASI_BRIGHTNESS, 50) self._camera.set_control_value(asi.ASI_FLIP, 0) self._camera.set_image_type(asi.ASI_IMG_RAW16) # Enabling stills mode try: # Force any single exposure to be halted self._camera.stop_video_capture() self._camera.stop_exposure() except (KeyboardInterrupt, SystemExit): raise except: pass # get initial window and binning self._binning = self._camera.get_bin() self._window = self._camera.get_roi()
def main1(self): asi.init(self.zwo_asi_lib) num_cameras = asi.get_num_cameras() if num_cameras == 0: logging.error('No cameras found') sys.exit(0) camera = asi.Camera(0) camera.set_control_value(asi.ASI_BANDWIDTHOVERLOAD, camera.get_controls()['BandWidth']['MinValue']) try: while True: self.take_exposure(camera, self.build_filename()) time.sleep(self.inter_exposure_delay_seconds) except KeyboardInterrupt: print('Manual break by user') except asi.ZWO_CaptureError as e: logging.error('Error capturing' + str(e))
def __init__(self): logging.basicConfig( format='%(asctime)s %(levelname)s:falcon ZWOcamera %(message)s', level=logging.INFO) logging.info("Starting falcon ZWO Camera Server") self.env_filename = os.getenv('ZWO_ASI_LIB') if self.env_filename: asi.init(self.env_filename) else: logging.error('The filename of the SDK library is required \ (or set ZWO_ASI_LIB environment variable with the filename)') sys.exit(1) num_cameras = asi.get_num_cameras() if num_cameras == 0: logging.error('No cameras found') sys.exit(0) cameras_found = asi.list_cameras( ) # Models names of the connected cameras if num_cameras == 1: camera_id = 0 logging.info('Found one camera: %s' % cameras_found[0]) else: logging.info('Found %d cameras' % num_cameras) for n in range(num_cameras): logging.info(' %d: %s' % (n, cameras_found[n])) # TO DO: allow user to select a camera camera_id = 0 logging.info('Using #%d: %s' % (camera_id, cameras_found[camera_id])) self.camera = asi.Camera(camera_id) self.initCamera() # Accept connections on all tcp addresses, port 5555 self.sender = imageTransport.ImageSender(connect_to='tcp://*:5555', REQ_REP=False) self.zmqcontext = zmq.Context() self.myCmdSocket = self.zmqcontext.socket(zmq.REP) self.myCmdSocket.bind("tcp://*:5556") self.RUN = True self.CMDThread = self.zmqQueue() signal.signal(signal.SIGINT, self.signal_handler)
def __init__(self): try: asi.init('/home/jllama/asi_software/lib/x64/libASICamera2.so') except: pass num_cameras = asi.get_num_cameras() if num_cameras == 0: print('No cameras found') sys.exit(0) self.camera = asi.Camera(0) self.camera_info = self.camera.get_camera_property() self.controls = self.camera.get_controls() self.camera.set_control_value( asi.ASI_BANDWIDTHOVERLOAD, self.camera.get_controls()['BandWidth']['MinValue']) self.camera.disable_dark_subtract() self.camera.set_control_value(asi.ASI_GAIN, 60) self.camera.set_control_value(asi.ASI_EXPOSURE, 1500) self.camera.set_control_value(asi.ASI_WB_B, 99) self.camera.set_control_value(asi.ASI_WB_R, 75) self.camera.set_control_value(asi.ASI_GAMMA, 50) self.camera.set_control_value(asi.ASI_BRIGHTNESS, 50) self.camera.set_control_value(asi.ASI_FLIP, 0)
def initialize_zwoasi(): env_filename = '/usr/local/lib/libASICamera2.so' asi.init(env_filename) num_cameras = asi.get_num_cameras() if num_cameras == 0: print('No cameras found') sys.exit(0) cameras_found = asi.list_cameras() # Models names of the connected cameras if num_cameras == 1: camera_id = 0 print('Found one camera: %s' % cameras_found[0]) else: print('Found %d cameras' % num_cameras) for n in range(num_cameras): print(' %d: %s' % (n, cameras_found[n])) # TO DO: allow user to select a camera camera_id = 0 print('Using #%d: %s' % (camera_id, cameras_found[camera_id])) return camera_id
if not len(sys.argv) > 1: help(parser, option_set) sys.exit(1) if args.help: help(parser, option_set) sys.exit(1) # At this point we can test for which args have been suppied by the user # and check for compatibility with each other, validate_args(vars(args)) # Initialize zwoasi with the name of the SDK library if args.zwolib: asi.init(args.zwolib) else: print('The path to the ZWO ASI SDK library is required (ASICamera2.dll)') sys.exit(1) num_cameras = asi.get_num_cameras() if num_cameras == 0: print('No cameras found') sys.exit(0) if (args.camera_id is not None): if (args.camera_id > num_cameras - 1): print('Invalid camera selected') sys.exit(0) camera = asi.Camera(args.camera_id)
def capture_asi(buf, z1, t1, z2, t2, nx, ny, nz, tend, device_id, live, gain, maxgain, autogain, exposure, bins, brightness, bandwidth, high_speed, hardware_bin, sdk): # Array flag first = True # Initialize device asi.init(sdk) camera = asi.Camera(device_id) camera_info = camera.get_camera_property() logger.info('ASI Camera info: %s' % camera_info) logger.info(camera_info['MaxHeight']) camera.set_control_value(asi.ASI_BANDWIDTHOVERLOAD, bandwidth) camera.disable_dark_subtract() camera.set_control_value(asi.ASI_GAIN, gain, auto=autogain) camera.set_control_value(asi.ASI_EXPOSURE, exposure, auto=False) camera.set_control_value(asi.ASI_AUTO_MAX_GAIN, maxgain) camera.set_control_value(asi.ASI_AUTO_MAX_BRIGHTNESS, 20) camera.set_control_value(asi.ASI_WB_B, 99) camera.set_control_value(asi.ASI_WB_R, 75) camera.set_control_value(asi.ASI_GAMMA, 50) camera.set_control_value(asi.ASI_BRIGHTNESS, brightness) camera.set_control_value(asi.ASI_FLIP, 0) camera.set_control_value(asi.ASI_HIGH_SPEED_MODE, high_speed) camera.set_control_value(asi.ASI_HARDWARE_BIN, hardware_bin) camera.set_roi(bins=binning) camera.start_video_capture() camera.set_image_type(asi.ASI_IMG_RAW8) # Fix autogain if autogain: while True: # Get frame z = camera.capture_video_frame() # Break on no change in gain settings = camera.get_control_values() if gain == settings["Gain"]: break gain = settings["Gain"] camera.set_control_value(asi.ASI_GAIN, gain, auto=autogain) # Loop until reaching end time while float(time.time()) < tend: # Get settings settings = camera.get_control_values() gain = settings["Gain"] temp = settings["Temperature"] / 10.0 logging.info("Capturing frame with gain %d, temperature %.1f" % (gain, temp)) # Set gain if autogain: camera.set_control_value(asi.ASI_GAIN, gain, auto=autogain) # Get frames for i in range(nz): # Store start time t0 = float(time.time()) # Get frame z = camera.capture_video_frame() # Compute mid time t = (float(time.time()) + t0) / 2.0 # Display Frame if live is True: cv2.imshow("Capture", z) cv2.waitKey(1) # Store results if first: z1[i] = z t1[i] = t else: z2[i] = z t2[i] = t # Assign buffer ready if first: buf.value = 1 else: buf.value = 2 # Swap flag first = not first # End capture logger.info("Exiting capture") camera.stop_video_capture()
y = y - yreference motionAnglex = abs(DECangle) motionAngley = abs(RAangle) xtrans = x * np.cos(motionAnglex * np.pi / 180) - y * np.sin( motionAnglex * np.pi / 180) ytrans = x * np.sin(motionAnglex * np.pi / 180) + y * np.cos( motionAnglex * np.pi / 180) #xtrans = x*np.cos(slopeDEC)+y*np.sin(slopeDEC) #ytrans = y*np.cos(slopeDEC)-x*np.sin(slopeDEC) StarTableTrans = np.append(StarTableTrans, np.array([[number, xtrans, ytrans, 1]]), axis=0) ################ Init everything ################################################################### asi.init("/lib/zwoasi/armv7/libASICamera2.so") camera = asi.Camera(0) global ExpTime global CamGain global tframe global tresh global TempCoordinates global StarTable global SearchIndikator global TrackIndikator global selectedStarNumber global selectedStar global selectedStarIndikator global calibIndi TempCoordinates = np.empty((0, 2), float) ExpTime = 100
def __init__(self): super().__init__() self.telescope = None self.camera = None self.guider = None self.wheel = None self.focuser = None self.telescope_thread = None self.camera_thread = None self.guider_thread = None self.menu = QtWidgets.QMenu() self.status_coords_label = QtWidgets.QLabel() self.setupUi(self) self.camera_settings_frame = ZWOSettings() self.camera_settings_action = QtWidgets.QWidgetAction(None) self.camera_settings_menu = QtWidgets.QMenu() self.camera_settings_menu.addAction(self.savelocation_action) self.camera_settings_btn.setMenu(self.camera_settings_menu) self.guider_settings_frame = ZWOSettings() self.guider_parameters_frame = GuiderParameters() self.guider_settings_action = QtWidgets.QWidgetAction(None) self.guider_settings_action.setDefaultWidget( self.guider_settings_frame) self.guider_parameters_action = QtWidgets.QWidgetAction(None) self.guider_parameters_action.setDefaultWidget( self.guider_parameters_frame) self.guider_menu = QtWidgets.QMenu() self.guider_menu.addAction(self.guider_parameters_action) self.guider_settings_btn.setMenu(self.guider_menu) self.mountmodes_tuple = ("Stop", "Home") # Models for schedule table columns. self.target_list_model = QtCore.QStringListModel() self.target_list_model.setStringList(self.mountmodes_tuple + appglobals.targets_tuple) # Schedule frame self.schedule_dockwindow = DockWindow(self, windowTitle='Schedule') self.schedule_dockwindow.setFeatures( self.schedule_dockwindow.features() & ~QtWidgets.QDockWidget.DockWidgetClosable) self.schedule_frame = ScheduleFrame(self) self.schedule_dockwindow.setWidget(self.schedule_frame) self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.schedule_dockwindow) # Guider frame self.guider_dockwindow = DockWindow(self, windowTitle='Guider') self.guider_dockwindow.setFeatures( self.guider_dockwindow.features() & ~QtWidgets.QDockWidget.DockWidgetClosable) self.guider_frame = GuiderFrame(self) self.guider_dockwindow.setWidget(self.guider_frame) self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.guider_dockwindow) # Camera frame self.camera_dockwindow = DockWindow(self, windowTitle='Camera') self.camera_dockwindow.setFeatures( self.camera_dockwindow.features() & ~QtWidgets.QDockWidget.DockWidgetClosable) self.camera_frame = CameraFrame(self) self.camera_dockwindow.setWidget(self.camera_frame) self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.camera_dockwindow) # Settings frame self.settings_dockwindow = DockWindow(self, windowTitle='Settings') self.settings_frame = SettingsFrame(self) self.settings_dockwindow.setWidget(self.settings_frame) self.addDockWidget(QtCore.Qt.RightDockWidgetArea, self.settings_dockwindow) self.telescope_action.toggled.connect( self.settings_frame.telescope_check_box.setChecked) self.guider_action.toggled.connect( self.settings_frame.guider_check_box.setChecked) self.camera_action.toggled.connect( self.settings_frame.camera_check_box.setChecked) self.wheel_action.toggled.connect( self.settings_frame.filter_wheel_check_box.setChecked) self.focuser_action.toggled.connect( self.settings_frame.focuser_check_box.setChecked) if sys.platform.startswith("win"): asi.init(str(sys.path[0]) + "\\lib\\ASICamera2.dll") self.setup_gui()
def get_Camera_photo(fileName): env_filename = os.getenv('ZWO_ASI_LIB') parser = argparse.ArgumentParser(description='Process and save images from a camera') parser.add_argument('filename', nargs='?', help='SDK library filename') args = parser.parse_args() # Initialize zwoasi with the name of the SDK library if args.filename: asi.init(args.filename) elif env_filename: asi.init(env_filename) else: print('The filename of the SDK library is required (or set ZWO_ASI_LIB environment variable with the filename)') sys.exit(1) num_cameras = asi.get_num_cameras() if num_cameras == 0: print('No cameras found') sys.exit(0) cameras_found = asi.list_cameras() # Models names of the connected cameras if num_cameras == 1: camera_id = 0 print('Found one camera: %s' % cameras_found[0]) else: print('Found %d cameras' % num_cameras) for n in range(num_cameras): print(' %d: %s' % (n, cameras_found[n])) # TO DO: allow user to select a camera camera_id = 0 print('Using #%d: %s' % (camera_id, cameras_found[camera_id])) camera = asi.Camera(camera_id) camera_info = camera.get_camera_property() # Get all of the camera controls 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]))) # Use minimum USB bandwidth permitted camera.set_control_value(asi.ASI_BANDWIDTHOVERLOAD, camera.get_controls()['BandWidth']['MinValue']) # Set some sensible defaults. They will need adjusting depending upon # the sensitivity, lens and lighting conditions used. camera.disable_dark_subtract() camera.set_control_value(asi.ASI_GAIN, 150) camera.set_control_value(asi.ASI_EXPOSURE, 20000) camera.set_control_value(asi.ASI_WB_B, 99) camera.set_control_value(asi.ASI_WB_R, 75) camera.set_control_value(asi.ASI_GAMMA, 50) camera.set_control_value(asi.ASI_BRIGHTNESS, 50) camera.set_control_value(asi.ASI_FLIP, 0) print('Enabling stills mode') try: # Force any single exposure to be halted camera.stop_video_capture() camera.stop_exposure() except (KeyboardInterrupt, SystemExit): raise except: pass print('Capturing a single 8-bit mono image') filename =fileName+ '_image_mono.jpg' camera.set_image_type(asi.ASI_IMG_RAW8) camera.capture(filename=filename) print('Saved to %s' % filename) save_control_values(filename, camera.get_control_values()) print('Capturing a single 16-bit mono image') filename = 'image_mono16.tiff' camera.set_image_type(asi.ASI_IMG_RAW16) camera.capture(filename=filename) print('Saved to %s' % filename) save_control_values(filename, camera.get_control_values()) if camera_info['IsColorCam']: filename = fileName+'image_color.jpg' camera.set_image_type(asi.ASI_IMG_RGB24) print('Capturing a single, color image') camera.capture(filename=filename) print('Saved to %s' % filename) save_control_values(filename, camera.get_control_values()) else: print('Color image not available with this camera') # Enable video mode try: # Force any single exposure to be halted camera.stop_exposure() except (KeyboardInterrupt, SystemExit): raise except: pass print('Enabling video mode') camera.start_video_capture() # Restore all controls to default values except USB bandwidth for c in controls: if controls[c]['ControlType'] == asi.ASI_BANDWIDTHOVERLOAD: continue camera.set_control_value(controls[c]['ControlType'], controls[c]['DefaultValue']) # Can autoexposure be used? k = 'Exposure' if 'Exposure' in controls and controls['Exposure']['IsAutoSupported']: print('Enabling auto-exposure mode') camera.set_control_value(asi.ASI_EXPOSURE, controls['Exposure']['DefaultValue'], auto=True) if 'Gain' in controls and controls['Gain']['IsAutoSupported']: print('Enabling automatic gain setting') camera.set_control_value(asi.ASI_GAIN, controls['Gain']['DefaultValue'], auto=True) # Keep max gain to the default but allow exposure to be increased to its maximum value if necessary camera.set_control_value(controls['AutoExpMaxExpMS']['ControlType'], controls['AutoExpMaxExpMS']['MaxValue']) print('Waiting for auto-exposure to compute correct settings ...') sleep_interval = 0.100 df_last = None gain_last = None exposure_last = None matches = 0 while True: time.sleep(sleep_interval) settings = camera.get_control_values() df = camera.get_dropped_frames() gain = settings['Gain'] exposure = settings['Exposure'] if df != df_last: print(' Gain {gain:d} Exposure: {exposure:f} Dropped frames: {df:d}' .format(gain=settings['Gain'], exposure=settings['Exposure'], df=df)) if gain == gain_last and exposure == exposure_last: matches += 1 else: matches = 0 if matches >= 5: break df_last = df gain_last = gain exposure_last = exposure # Set the timeout, units are ms timeout = (camera.get_control_value(asi.ASI_EXPOSURE)[0] / 1000) * 2 + 500 camera.default_timeout = timeout if camera_info['IsColorCam']: print('Capturing a single color frame') filename = 'image_video_color.jpg' camera.set_image_type(asi.ASI_IMG_RGB24) camera.capture_video_frame(filename=filename) else: print('Capturing a single 8-bit mono frame') filename = 'image_video_mono.jpg' camera.set_image_type(asi.ASI_IMG_RAW8) camera.capture_video_frame(filename=filename) print('Saved to %s' % filename) save_control_values(filename, camera.get_control_values())
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) env_filename = os.getenv('ZWO_ASI_LIB') parser = argparse.ArgumentParser( description='Process and save images from a camera') parser.add_argument('filename', nargs='?', help='SDK library filename') args = parser.parse_args() # Initialize zwoasi with the name of the SDK library if args.filename: asi.init(args.filename) elif env_filename: asi.init(env_filename) else: print( 'The filename of the SDK library is required (or set ZWO_ASI_LIB environment variable with the filename)' ) sys.exit(1) num_cameras = asi.get_num_cameras() if num_cameras == 0: print('No cameras found') sys.exit(0) cameras_found = asi.list_cameras() # Models names of the connected cameras
self.camera.stop_video_capture() self.camera.stop_exposure() except (KeyboardInterrupt, SystemExit): raise except: pass return self.camera.capture() if __name__ == "__main__": syslog(LOG_INFO, 'Start server') libasi_path = '/opt/ASI_SDK/lib/armv7/libASICamera2.so' asi.init(libasi_path) try: camera0 = asi.Camera(0) ccd = CameraHandler(camera0) syslog(LOG_INFO, 'Camera found') except: syslog(LOG_ERR, 'Camera not found') sys.exit(EC_CAMERA_NOT_FOUND) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) sock.bind((HOST_ADDRESS, HOST_PORT)) sock.listen(2)
gain = "Gain: " + str(sli_gain.get()) cv2.rectangle(frame, (0, 0), (1600, 200), (0, 0, 0), cv2.FILLED, cv2.FILLED, 1) cv2.putText(frame, heading, (20, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2, cv2.LINE_AA) cv2.putText(frame, exposure, (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1, cv2.LINE_AA) cv2.putText(frame, gain, (20, 70), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1, cv2.LINE_AA) cv2.putText(frame, strftime("%c"), (20, 90), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 1, cv2.LINE_AA) return frame config = AstroConfig() asi.init(config.settings['libpath']) window = tk.Tk() window.title(title) greeting = tk.Label(text=title) greeting.pack() sli_exposure = tk.Scale(window, from_=100, to=20000, orient=tk.HORIZONTAL, resolution=100, command=update_exposure, length=400) sli_exposure.set(5000) sli_exposure.pack() sli_gain = tk.Scale(window,
def capture_asi(image_queue, z1, t1, z2, t2, nx, ny, nz, tend, device_id, live, cfg): first = True # Array flag slow_CPU = False # Performance issue flag camera_type = "ASI" gain = cfg.getint(camera_type, 'gain') maxgain = cfg.getint(camera_type, 'maxgain') autogain = cfg.getboolean(camera_type, 'autogain') exposure = cfg.getint(camera_type, 'exposure') binning = cfg.getint(camera_type, 'bin') brightness = cfg.getint(camera_type, 'brightness') bandwidth = cfg.getint(camera_type, 'bandwidth') high_speed = cfg.getint(camera_type, 'high_speed') hardware_bin = cfg.getint(camera_type, 'hardware_bin') sdk = cfg.get(camera_type, 'sdk') # Initialize device asi.init(sdk) num_cameras = asi.get_num_cameras() if num_cameras == 0: logger.error("No ZWOASI cameras found") raise ValueError sys.exit() cameras_found = asi.list_cameras() # Models names of the connected cameras if num_cameras == 1: device_id = 0 logger.info("Found one camera: %s" % cameras_found[0]) else: logger.info("Found %d ZWOASI cameras" % num_cameras) for n in range(num_cameras): logger.info(" %d: %s" % (n, cameras_found[n])) logger.info("Using #%d: %s" % (device_id, cameras_found[device_id])) camera = asi.Camera(device_id) camera_info = camera.get_camera_property() logger.debug("ASI Camera info:") for (key, value) in camera_info.items(): logger.debug(" %s : %s" % (key, value)) camera.set_control_value(asi.ASI_BANDWIDTHOVERLOAD, bandwidth) camera.disable_dark_subtract() camera.set_control_value(asi.ASI_GAIN, gain, auto=autogain) camera.set_control_value(asi.ASI_EXPOSURE, exposure, auto=False) camera.set_control_value(asi.ASI_AUTO_MAX_GAIN, maxgain) camera.set_control_value(asi.ASI_AUTO_MAX_BRIGHTNESS, 20) camera.set_control_value(asi.ASI_WB_B, 99) camera.set_control_value(asi.ASI_WB_R, 75) camera.set_control_value(asi.ASI_GAMMA, 50) camera.set_control_value(asi.ASI_BRIGHTNESS, brightness) camera.set_control_value(asi.ASI_FLIP, 0) camera.set_control_value(asi.ASI_HIGH_SPEED_MODE, high_speed) camera.set_control_value(asi.ASI_HARDWARE_BIN, hardware_bin) camera.set_roi(bins=binning) camera.start_video_capture() camera.set_image_type(asi.ASI_IMG_RAW8) try: # Fix autogain if autogain: while True: # Get frame z = camera.capture_video_frame() # Break on no change in gain settings = camera.get_control_values() if gain == settings["Gain"]: break gain = settings["Gain"] camera.set_control_value(asi.ASI_GAIN, gain, auto=autogain) # Loop until reaching end time while float(time.time()) < tend: # Wait for available capture buffer to become available if (image_queue.qsize() > 1): logger.warning( "Acquiring data faster than your CPU can process") slow_CPU = True while (image_queue.qsize() > 1): time.sleep(0.1) if slow_CPU: lost_video = time.time() - t logger.info("Waited %.3fs for available capture buffer" % lost_video) slow_CPU = False # Get settings settings = camera.get_control_values() gain = settings["Gain"] temp = settings["Temperature"] / 10.0 logger.info("Capturing frame with gain %d, temperature %.1f" % (gain, temp)) # Set gain if autogain: camera.set_control_value(asi.ASI_GAIN, gain, auto=autogain) # Get frames for i in range(nz): # Store start time t0 = float(time.time()) # Get frame z = camera.capture_video_frame() # Compute mid time t = (float(time.time()) + t0) / 2.0 # Display Frame if live is True: cv2.imshow("Capture", z) cv2.waitKey(1) # Store results if first: z1[i] = z t1[i] = t else: z2[i] = z t2[i] = t if first: buf = 1 else: buf = 2 image_queue.put(buf) logger.debug("Captured buffer %d" % buf) # Swap flag first = not first reason = "Session complete" except KeyboardInterrupt: print() reason = "Keyboard interrupt" except ValueError as e: logger.error("%s" % e) reason = "Wrong image dimensions? Fix nx, ny in config." except MemoryError as e: logger.error("Capture: Memory error %s" % e) finally: # End capture logger.info("Capture: %s - Exiting" % reason) camera.stop_video_capture() camera.close()
import numpy import math import distutils.dir_util from PIL import Image, ImageDraw, ImageFont, ImageMath, ImageChops env_filename = os.getenv('ZWO_ASI_LIB') fontfile = "/usr/share/fonts/truetype/ttf-bitstream-vera/VeraBd.ttf" fontsize = 12 font = ImageFont.truetype(fontfile, fontsize) # Initialize zwoasi with the name of the SDK library if env_filename: asi.init(env_filename) else: print( 'The filename of the SDK library is required set ZWO_ASI_LIB environment variable with the filename' ) sys.exit(1) num_cameras = asi.get_num_cameras() if num_cameras == 0: print('No cameras found') sys.exit(0) cameras_found = asi.list_cameras() # Models names of the connected cameras if num_cameras == 1: camera_id = 0
def initCamera(cam_width=320, cam_height=240): env_filename = os.getenv('ZWO_ASI_LIB') parser = argparse.ArgumentParser(description='Crescent moon detector') parser.add_argument('filename', nargs='?', help='SDK library filename') args = parser.parse_args() # Initialize zwoasi with the name of the SDK library if args.filename: asi.init(args.filename) elif env_filename: asi.init(env_filename) else: print( 'The filename of the SDK library is required (or set ZWO_ASI_LIB environment variable with the filename)' ) sys.exit(1) num_cameras = asi.get_num_cameras() if num_cameras == 0: print('No cameras found') sys.exit(0) cameras_found = asi.list_cameras() # Models names of the connected cameras if num_cameras == 1: camera_id = 0 camera_name = cameras_found[0] print('Found one camera: %s' % cameras_found[0]) else: print('Found %d cameras' % num_cameras) for n in range(num_cameras): print(' %d: %s' % (n, cameras_found[n])) # TO DO: allow user to select a camera camera_id = 0 print('Using #%d: %s' % (camera_id, cameras_found[camera_id])) camera = asi.Camera(camera_id) camera_info = camera.get_camera_property() # Get all of the camera controls controls = camera.get_controls() # Use minimum USB bandwidth permitted camera.set_control_value(asi.ASI_BANDWIDTHOVERLOAD, camera.get_controls()['BandWidth']['MinValue']) # Set some sensible defaults. They will need adjusting depending upon # the sensitivity, lens and lighting conditions used. camera.disable_dark_subtract() camera.set_control_value(asi.ASI_GAIN, 150) camera.set_control_value(asi.ASI_EXPOSURE, 49) camera.set_control_value(asi.ASI_WB_B, 99) camera.set_control_value(asi.ASI_WB_R, 75) camera.set_control_value(asi.ASI_GAMMA, 50) camera.set_control_value(asi.ASI_BRIGHTNESS, 50) camera.set_control_value(asi.ASI_FLIP, 0) # Restore all controls to default values except USB bandwidth for c in controls: if controls[c]['ControlType'] == asi.ASI_BANDWIDTHOVERLOAD: continue camera.set_control_value(controls[c]['ControlType'], controls[c]['DefaultValue']) # Can autoexposure be used? # k = 'Exposure' # if 'Exposure' in controls and controls['Exposure']['IsAutoSupported']: # print('Enabling auto-exposure mode') # camera.set_control_value(asi.ASI_EXPOSURE, # controls['Exposure']['DefaultValue'], # auto=True) if 'Gain' in controls and controls['Gain']['IsAutoSupported']: print('Enabling automatic gain setting') camera.set_control_value(asi.ASI_GAIN, controls['Gain']['DefaultValue'], auto=True) # Keep max gain to the default but allow exposure to be increased to its maximum value if necessary camera.set_control_value(controls['AutoExpMaxExpMS']['ControlType'], controls['AutoExpMaxExpMS']['MaxValue']) camera.set_image_type(asi.ASI_IMG_RAW8) camera.set_roi(width=cam_width, height=cam_height) return camera, camera_name
settings["type"] = f"{asi.ASI_IMG_RGB24}" # Number of images if args.number is not None: nimg = args.number else: nimg = 6 # Check path path = os.path.abspath(args.path) if not os.path.exists(path): os.makedirs(path) # Intialize SDK library try: asi.init(os.getenv("ZWO_ASI_LIB")) except Exception as e: print(e) sys.exit(1) # Find cameras ncam = asi.get_num_cameras() if ncam == 0: print("No ZWO ASI cameras found") sys.exit(1) # Decode settings texp_us = 1000 * int(settings["exposure"]) gain = int(settings["gain"]) # Initialize camera 0
def __init__(self): env_filename = os.getenv('ZWO_ASI_LIB') parser = argparse.ArgumentParser( description='Process and save images from a camera') parser.add_argument('filename', nargs='?', help='SDK library filename') args = parser.parse_args() args.filename = '../ZWO_ASI_Library/lib/armv7/libASICamera2.so' #args.filename = '../ZWO_ASI_Library/lib/mac/libASICamera2.dylib'; # mac case # Initialize zwoasi with the name of the SDK library if args.filename: asi.init(args.filename) elif env_filename: asi.init(env_filename) else: print( 'The filename of the SDK library is required (or set ZWO_ASI_LIB environment variable with the filename)' ) sys.exit(1) num_cameras = asi.get_num_cameras() if num_cameras == 0: print('No cameras found') sys.exit(0) cameras_found = asi.list_cameras( ) # Models names of the connected cameras if num_cameras == 1: camera_id = 0 print('Found one camera: %s' % cameras_found[0]) else: print('Found %d cameras' % num_cameras) for n in range(num_cameras): print(' %d: %s' % (n, cameras_found[n])) # TO DO: allow user to select a camera camera_id = 0 print('Using #%d: %s' % (camera_id, cameras_found[camera_id])) camera = asi.Camera(camera_id) camera_info = camera.get_camera_property() # Get all of the camera controls 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]))) # Use maximum USB bandwidth permitted camera.set_control_value( asi.ASI_BANDWIDTHOVERLOAD, camera.get_controls()['BandWidth']['MaxValue']) # Set some sensible defaults. They will need adjusting depending upon # the sensitivity, lens and lighting conditions used. camera.disable_dark_subtract() camera.set_control_value(asi.ASI_GAIN, 0) camera.set_control_value(asi.ASI_EXPOSURE, 10000) camera.set_control_value(asi.ASI_WB_B, 99) camera.set_control_value(asi.ASI_WB_R, 75) camera.set_control_value(asi.ASI_GAMMA, 50) camera.set_control_value(asi.ASI_BRIGHTNESS, 50) camera.set_control_value(asi.ASI_FLIP, 0) camera.set_image_type(asi.ASI_IMG_Y8) self.camera = camera