Exemplo n.º 1
2
def takePictures(directory, interval):
  camera = PiCamera()
  while(True):
    dateNow  = datetime.now(timezone('US/Central'))
    filename = dateNow.strftime('%Y-%m-%d-%H-%M-%S') + '.jpg'
    camera.capture(directory + '/' + filename)
    sleep(interval)
Exemplo n.º 2
1
def main():
   global preview

   parse_args(sys.argv[1:])
   cam = PiCamera()
   cam.rotation = -90
   cam.resolution = (width, height)
   cam.framerate = 60
   rawCapture = PiRGBArray(cam, size=(width, height))

   startTime = time.time()
   endTime = time.time() + capTime
   frames = 0

   for image in cam.capture_continuous(rawCapture, format="bgr", use_video_port=True):
      if image is None:
         print 'capture failed'
         break
      frames += 1
      frame = image.array

      if preview: 
         cv2.imshow("frame", frame)
         key = cv2.waitKey(1) & 0xFF


      if time.time() > endTime:
         break
      rawCapture.truncate(0)

   print "Average Framerate for " + str(frames) + \
      " frames was: " + str(float(frames) / capTime) + "fps"
   cv2.destroyAllWindows()
def getImage():
     # initialize the camera and grab a reference to the raw camera capture
     camera = PiCamera()
     camera.resolution = (640, 480)
     camera.framerate = 32
     rawCapture = PiRGBArray(camera, size=(640, 480))

     # print("setting is end!")

     # allow the camera to warmup
     # time.sleep(0.1)
     dst = None
     # capture frames from the camera
     for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
	# grab the raw NumPy array representing the image, then initialize the timestamp
	# and occupied/unoccupied text
	image = frame.array

	mtx =np.array([[100, 0, 320], [0, 100, 240], [0, 0, 1]], dtype=np.float32)  
	dist = np.array([-0.009, 0.0, 0.0, 0.0], dtype=np.float32)
	h,  w = image.shape[:2]
	newcameramtx, roi=cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))
	# undistort
	dst = cv2.undistort(image, mtx, dist, None, newcameramtx)
       break

     return dst
Exemplo n.º 4
0
class Camera(object):
    '''
    classdocs
    '''

    def __init__(self, number, led_pin):
        '''
        Constructor
        '''
        self.__cameraNumber = number
        self.__led_pin = led_pin
        self.__camera = PiCamera()
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(led_pin, GPIO.OUT)

        
    def capture(self):
        '''
        '''
        GPIO.output(self.__led_pin, GPIO.HIGH)
        time.sleep(0.1)
        rawCapture = PiRGBArray(self.__camera)
        # allow the camera to warmup
        time.sleep(0.1)
        self.__camera.capture(rawCapture, format="bgr")
        image = rawCapture.array
        time.sleep(0.1)
        GPIO.output(self.__led_pin, GPIO.LOW)
            
        return image
Exemplo n.º 5
0
	def __init__(self, color, color_params_initial={'b1': 0,'g1': 0,'r1': 0,'b2': 255,'g2': 255,'r2': 255}):

		self.color = color
		self.window_name = "Set " + self.color + " Ranges"

		self.image = None
		if platform.system() == 'Linux':
		    from picamera.array import PiRGBArray
		    from picamera import PiCamera
		    
		    camera = PiCamera()
		    time.sleep(0.25)
		    camera.resolution = (1120, 630)
		    rawCapture = PiRGBArray(camera, size=(1120, 630))

		    camera.capture(rawCapture, format="bgr")
		    self.image = rawCapture.array
		else:
		    camera = cv2.VideoCapture(0)
		    time.sleep(0.25)
		    (grabbed, image) = camera.read()
		    if not grabbed:
		    	raise Exception('Couldn\'t grab snapshot.' )
		    self.image = image

		self.params = color_params_initial
		self.build_sliders()
Exemplo n.º 6
0
class CameraRule(Rule):
    """ represents the rule that will take pictures """

    def __init__(self, periodicity, displays):
        super().__init__('CAMERA_RULE', periodicity)
        self.displays = displays
        self.camera = PiCamera()

    def create_image(self):
        now = datetime.now()

        filename = now.strftime("%H.%M.%S_%Y-%m-%d.jpg")
        path = '{0}_{1}'.format(now.month, now.day)

        distutils.dir_util.mkpath(path)
        self.camera.capture(os.path.join(path, filename))

    def execute(self):
        self.create_image()
        sleep(5)

        for display in self.displays:
            display.write(0)
            sleep(0.5)
            display.write(10)
            sleep(0.5)
            display.write(0)
Exemplo n.º 7
0
class PiVideoStream:
	def __init__(self, resolution=(320, 240), framerate=32):
		# initialize the camera and stream
		self.camera = PiCamera()
		self.camera.resolution = resolution
		self.camera.framerate = framerate
		self.rawCapture = PiRGBArray(self.camera, size=resolution)
		self.stream = self.camera.capture_continuous(self.rawCapture,
			format="bgr", use_video_port=True)

		# initialize the frame and the variable used to indicate
		# if the thread should be stopped
		self.frame = None
		self.stopped = False
	
	def __init__(self, resolution=(320, 240), framerate=32, rotate=0):
		# initialize the camera and stream
		self.camera = PiCamera()
		self.camera.rotation = rotate
		self.camera.resolution = resolution
		self.camera.framerate = framerate
		self.rawCapture = PiRGBArray(self.camera, size=resolution)
		self.stream = self.camera.capture_continuous(self.rawCapture,
			format="bgr", use_video_port=True)

		# initialize the frame and the variable used to indicate
		# if the thread should be stopped
		self.frame = None
		self.stopped = False

	def start(self):
		# start the thread to read frames from the video stream
		t = Thread(target=self.update, args=())
		t.daemon = True
		t.start()
		return self

	def update(self):
		# keep looping infinitely until the thread is stopped
		for f in self.stream:
			# grab the frame from the stream and clear the stream in
			# preparation for the next frame
			self.frame = f.array
			self.rawCapture.truncate(0)

			# if the thread indicator variable is set, stop the thread
			# and resource camera resources
			if self.stopped:
				self.stream.close()
				self.rawCapture.close()
				self.camera.close()
				return

	def read(self):
		# return the frame most recently read
		return self.frame

	def stop(self):
		# indicate that the thread should be stopped
		self.stopped = True
Exemplo n.º 8
0
    def _captureBayer(shutter_speed):
        camera = None
        try:
            camera = PiCamera()
            _setup_camera(camera, _max_resolution, shutter_speed, _iso)

            rawCapture = PiBayerArray(camera)
            print("capture...")
            bayerCapture = PiBayerArray(camera)
            camera.capture(bayerCapture, "jpeg", bayer=True)  # grab the 10 bit resolution with the raw bayer data

            imageBayer = bayerCapture.demosaic()
            print("done")

        except:
            if camera is None:
                raise Exception("Failed to initialize PiCamera.")
            else:
                raise Exception("Failed to capture image.")

        finally:
            if camera is not None:
                camera.close()

        return imageBayer
Exemplo n.º 9
0
def rpiCapture(opts):

    global _frame
    global _frameCounter

    # initialize the camera and grab a reference to the raw camera capture
    camera= PiCamera()
    camera.resolution = CAPTURE_RES 
    camera.framerate = 4 
    rawCapture = PiRGBArray(camera, size=CAPTURE_RES)
    
    # allow the camera to warmup
    time.sleep(0.1)
     
    # capture frames from the camera
    for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True) :
	# grab the raw NumPy array representing the image, then initialize the timestamp
	# and occupied/unoccupied text
        with _frameLock :
            #copy frame handled by video capturing structure, so it won't be modified by next captures
            _frame = numpy.copy(frame.array)
            if(_frameCounter == 0) :
                initStream(frame, opts)
            _frameCounter += 1

	    # clear the stream in preparation for the next frame
        rawCapture.truncate(0)    
        
        if _stopThreads :
            return
Exemplo n.º 10
0
class Capture(threading.Thread):
  def __init__(self, threadID, name, queue, config):
    threading.Thread.__init__(self)
    self.threadID = threadID
    self.name = name
    self.queue = queue
    self.config = config
    self.exit = threading.Event()
    self.totalframes = 0


  def run(self):
    # initialize camera
    try:
      self.camera = PiCamera()
      self.camera.resolution = (int(self.config.get('rpi-art', 'width')), int(self.config.get('rpi-art', 'height')))
      self.camera.framerate = 12
      rawCapture = PiRGBArray(self.camera, size=(int(self.config.get('rpi-art', 'width')), int(self.config.get('rpi-art', 'height'))))
      time.sleep(1)
    except:
      print "Error opening camera"
      exit(1)
    # add frames to queue
    for frame in self.camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
      self.queue.put(frame.array)
      self.totalframes += 1
      if self.config.getboolean('rpi-art', 'debug'):
        print "Captured frame", self.totalframes
      rawCapture.truncate(0)
      if self.exit.is_set():
        break
    self.camera.close()
Exemplo n.º 11
0
class VideoCamera(object):
    def __init__(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        # instead.
        #self.video = cv2.VideoCapture(0)
        self.camera = PiCamera()
        #self.rawCapture = PiRGBArray(self.camera)
        self.camera.resolution = (640, 480)
        self.camera.framerate = 32
        self.rawCapture = PiRGBArray(self.camera, size=(640, 480))
 
        
        # allow the camera to warmup
        time.sleep(0.1)

        # If you decide to use video.mp4, you must have this file in the folder
        # as the main.py.
        # self.video = cv2.VideoCapture('video.mp4')
    
    def __del__(self):
        #self.video.release()
        pass
    
    def get_frame(self):
        # grab an image from the camera
        self.camera.capture(self.rawCapture, format="bgr")
        image = self.rawCapture.array
        self.rawCapture.truncate(0) 
        # We are using Motion JPEG, but OpenCV defaults to capture raw images,
        # so we must encode it into JPEG in order to correctly display the
        # video stream.
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tostring()
Exemplo n.º 12
0
def init_camera():
    global camera, rawCapture
    camera = PiCamera()
    camera.resolution = (1280, 720)

    rawCapture = PiRGBArray(camera)
    print("Recognizer: Camera initialized")
Exemplo n.º 13
0
def generate(centeoid0, centroid1):
    


# initialize the cameras and grab reference to the raw camera capture
camera = PiCamera()      # create an instance of the PiCamera class
gocam(0)
rawCapture0 = PiRGBArray(camera)
gocam(1)
rawCapture1 = PiRGBArray(camera)

# allow the cameras to warmup
time.sleep(0.1)


# ------  main loop start here  ------

loopFlag = 1
while loopFlag == 1 :
    # load the image from camera 0
    gocam(0)
    camera.capture(rawCapture0, format="bgr")
    image0 = rawCapture0.array

    # load the image from camera 1
    gocam(1)
    camera.capture(rawCapture1, format="bgr")
    image1 = rawCapture1.array

    # image proccessing and analyse the object special location
    obj0 = getobj(image0)
    obj1 = getobj(image1)
    cent0X, cent0Y = getcent(obj0)
    cent1X, cent1Y = getcent(obj1)
    objDistance, objHorizonalOffset = getposition(cent0, cent1)
Exemplo n.º 14
0
class PiCameraAction( AbstractAction ) :

    def __init__( self ) :
        #AbstractAction.__init__(self)
        self.camera = None

    def do_GET(self, handler) :

        try :
            self.ensure_camera()
            self.camera.capture( handler.wfile, 'jpeg' )
            handler.wfile.close()

        except Exception as e :
            print "Failed to take a photo"
            print(traceback.format_exc())
            self.camera = None
            self.error( handler, "Failed to take a photo" )

    def ensure_camera( self ) :
        if self.camera:
            return

        self.camera = PiCamera( resolution=(640,480) )
        self.camera.start_preview()
        # Camera warm-up time
        time.sleep(2)
Exemplo n.º 15
0
class FrameGrabber(threading.Thread):
    def __init__(self, frameQueue, angleQueue):
        threading.Thread.__init__(self)
        self.frameQueue = frameQueue
        self.angleQueue = angleQueue
        self.camera = PiCamera()
        self.camera.hflip = CAMERA_HFLIP
        self.camera.vflip = CAMERA_VFLIP          
        self.camera.resolution = (CAMERA_WIDTH, CAMERA_HEIGHT)
        self.camera.framerate = CAMERA_FRAMERATE
        self.rawCapture = PiRGBArray(self.camera, size=(CAMERA_WIDTH, CAMERA_HEIGHT))
        self.startCaptureTime = time.time()
        self.sc = ServoController()

    def run(self):
        # allow the camera to warmup
        runtime = time.time()
        sleeptime = min(runtime - self.startCaptureTime,1)
        time.sleep(sleeptime)

        # capture frames from the camera
        while not shutdownEvent.isSet():
            angle = self.angleQueue.get(block=True)
            self.sc.setCameraAngle(angle)
            ts = time.time()
            self.camera.capture(self.rawCapture, format='bgr', use_video_port=True)
            self.frameQueue.put((ts,self.rawCapture.array,angle))
            self.rawCapture.truncate(0)
Exemplo n.º 16
0
class PiCamIface(Iface):
    """ Read from raspberry pi camera.

            :param name: name of interface (str), default 'picam'
            :param source: id of device, dummy not used yet, default = 0
    """
    def __init__(self, name='picam', source=0):
        """ Constructor
        """
        super(PiCamIface, self).__init__(name)
        self.source = source
        self.video = None
        self.camera = PiCamera()
        self.rawCapture = PiRGBArray(self.camera)

    def __del__(self):
        """ Destructor
        """
        self.camera.close()

    def GetImage(self):
        """ Get image from stream

            :returns: an image or None
        """
        if self.state == self.IF_OK:
            self.camera.capture(self.rawCapture, format="bgr")
            img = self.rawCapture.array
            if img is None:
                self.state = self.IF_EOF
                logging.warning(" eof on video source")
            return img
        return None
Exemplo n.º 17
0
def initialize_camera(camera, res):
    """
    Initializes this camera using current time to set framerate
    :param res: image resolution to use
    :return: None
    """

    try:  # Release the camera resources if already exist
        camera.close()
    except AttributeError:  # Camera doesn't already exist
        pass

    camera = PiCamera()
    camera.resolution = res
    set_framerate_by_time(FPS, TIME_ON, camera)  # Set initial frame rate.
    camera.vflip = False
    camera.hflip = False
    camera.rotate = 90

    rawCapture = PiRGBArray(camera, size=camera.resolution)
    time.sleep(0.9)  # allow the camera to warm up

    print("Camera initialized")

    return camera, rawCapture
Exemplo n.º 18
0
def main():
	args = get_arguments()
	range_filter = args['filter'].upper()
	camera = PiCamera()
	camera.resolution = (640, 480)
	camera.framerate = 32
	rawCapture = PiRGBArray(camera, size=(640, 480))
	setup_trackbars(range_filter)

	while True:
		if args['webcam']:
			for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
				# grab the raw NumPy array representing the image, then initialize the timestamp
				# and occupied/unoccupied text
				image = frame.array

			if range_filter == 'RGB':
				frame_to_thresh = image.copy()
			else:
				frame_to_thresh = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

		v1_min, v2_min, v3_min, v1_max, v2_max, v3_max = get_trackbar_values(range_filter)

		thresh = cv2.inRange(frame_to_thresh, (v1_min, v2_min, v3_min), (v1_max, v2_max, v3_max))

		cv2.imshow("Original", image)
		cv2.imshow("Thresh", thresh)

		if cv2.waitKey(1) & 0xFF is ord('q'):
			break
Exemplo n.º 19
0
class CamThread(Thread):
	""" Thread to continuously read incoming frames from the raspberry pi camera
		and send those frames to all the clients connected to the server.
	"""
	def __init__(self):
		print 'init CamThread'
		self.cam = PiCamera()
		self.cam.resolution = (480,320)
		self.cam.framerate = 25
		self.rawCap = PiRGBArray(self.cam)
		# Wait for the webcam to open
		sleep(0.2)

		self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

		Thread.__init__(self)
		self.daemon = True
		self.running = True

	def run(self):
		print 'CamThread running'
		for frame in self.cam.capture_continuous(self.rawCap, format='bgr', use_video_port=True):
			if not self.running:
				break

			img = self.rawCap.array
			rows, cols, channels = img.shape

			if rows > 0 and cols > 0:
				# 180 degrees rotation
				img = self.rotate(img, 180)

				# Serialize and send
				img_ser = self.encode(img, '.jpg')
				for c in connected_clients:
					self.send(img_ser, (c, CLIENT_PORT))
			# Clear the camera buffer begore grabbing the next frame
			self.rawCap.truncate(0)
		self.sock.close()
		self.cam.close()

	def encode(self, img, ext='.jpg'):
		return cv2.imencode(ext, img)[1].tostring()

	def rotate(self, frame, angle):
		rows, cols, channels = frame.shape
		RotMat = cv2.getRotationMatrix2D((cols/2, rows/2), angle, 1)
		return cv2.warpAffine(frame, RotMat, (cols, rows))

	def send(self, data, addr):
		# Send the data splitted in oackets of 1024 bytes
		while len(data) > 1024:
			self.sock.sendto(data[:1024], addr)
			data = data[1024:]
		if len(data) > 0:
			self.sock.sendto(data, addr)

	def stop(self):
		self.running = False
Exemplo n.º 20
0
def initCam():
    # initialize the camera and grab a reference to the raw camera capture
    camera = PiCamera()
    camera.resolution = (tools.SIZE_X, tools.SIZE_Y)
    #camera.framerate = 64
    rawCapture = PiRGBArray(camera, size=(tools.SIZE_X, tools.SIZE_Y))
    # allow the camera to warmup
    time.sleep(0.1)
    return camera, rawCapture
Exemplo n.º 21
0
def initcam(pi_cam=False):
    if pi_cam:
        from picamera.array import PiRGBArray
        from picamera import PiCamera
        camera = PiCamera()
        camera.resolution = (320, 240)
        raw = PiRGBArray(camera)
        return camera, raw
    return cv2.VideoCapture(0)
Exemplo n.º 22
0
class OpenCVTEST:
    def __init__(self):
        # initialize the camera and grab a reference to the raw camera capture
        factor = 1.5
        self.camera = PiCamera()
        self.camera.resolution = (640, 480)
        self.camera.framerate = 32
        self.rawCapture = PiRGBArray(self.camera, size=(640, 480))
        # allow the camera to warmup
        time.sleep(0.1)
        cv2.namedWindow("Video")

        self.pictureBuffer = deque()

        self.currentPicture = None
        self.firstPicture = None

    def showPicture(self, picture):
        cv2.imshow("Video", picture)

    def addPicture(self, picture):
        self.pictureBuffer.append(picture)

    def getCurrentPicture(self):
        return self.currentPicture

    def getPicture(self):
        return self.pictureBuffer.popleft()

    def forePlay(self):
        number = 0
        for frame in self.camera.capture_continuous(self.rawCapture, format="bgr", use_video_port=True):
            # grab the raw NumPy array representing the image, then initialize the timestamp
            # and occupied/unoccupied text
            self.currentPicture = frame.array
            self.addPicture(self.currentPicture)
            self.rawCapture.truncate(0)

            number += 1
            if number >= 100:
                break
        self.play()

    def play(self):
        for frame in self.camera.capture_continuous(self.rawCapture, format="bgr", use_video_port=True):
            # grab the raw NumPy array representing the image, then initialize the timestamp
            # and occupied/unoccupied text
            self.currentPicture = frame.array
            self.addPicture(self.currentPicture)
            self.showPicture(self.getPicture())
            self.rawCapture.truncate(0)

            key = cv2.waitKey(1) & 0xFF
            if key == ord("q"):
                break
        print("Bye bye!")
Exemplo n.º 23
0
def Offset_Detect(offset_array):
    data=[0,0,0,0,0,0,0,0,0]	#三个一组 dx,dy,radius
    #global offset_array
    FRAME_WIDTH = 320
    FRAME_HEIGHT = 240

    HUE_BLUE = 240/2
    HUE_YELLOW = 60/2
    HUE_RED = 0
    HUE_RANGE = 10

    SAT_MIN = 100
    SAT_MAX = 255

    VAL_MIN = 50
    VAL_MAX = 255

    CLOSE_MASK_SIZE = 30
    KERNEL = np.ones((CLOSE_MASK_SIZE, CLOSE_MASK_SIZE), np.uint8)


    camera = PiCamera()
    camera.resolution = (FRAME_WIDTH, FRAME_HEIGHT)
    camera.framerate = 30
    camera.awb_mode = "incandescent"
    rawCapture = PiRGBArray(camera, size=(FRAME_WIDTH, FRAME_HEIGHT))
    time.sleep(0.1)

    last_time=0
    for rawFrame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
	#print 'alltime:',time.time()-last_time
	#last_time=time.time()

	input_frame = rawFrame.array
	correct_frame = calibration(input_frame)
	frame = cv2.resize(correct_frame, (120,90))

	hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
	#print '1time:',time.time()-last_time
	data[0:3]=processImage(hsv, 1, frame)
	#print '2time:',time.time()-last_time
	data[3:6]=processImage(hsv, 2, frame)
	#print '3time:',time.time()-last_time
	data[6:9]=processImage(hsv, 3, frame)
	#print '4time:',time.time()-last_time
	#print data
	offset_array[:]=data
	#print offset_data

	cv2.imshow("Frame", frame)
	next_frame(rawCapture)
	key=cv2.waitKey(1)&0xFF
	if key == 27:
	    break

    cv2.destroyAllWindows()
Exemplo n.º 24
0
    def PiVideo(self):
    # initialize the camera and grab a reference to the raw camera capture
        camera = PiCamera()
        camera.resolution = (640, 480)
        camera.framerate = 30

        # allow the camera to warmup
        time.sleep(2)

        return camera
Exemplo n.º 25
0
def snapshot():
    if not os.path.exists('/home/pi/OSecuritySnapshots'):
        os.makedirs('/home/pi/OSecuritySnapshots')
    camera = PiCamera()
    camera.rotation = -90
    camera.start_preview()
    sleep (3)
    camera.capture('/home/pi/OSecuritySnapshots/latestSnapshot.JPG')
    camera.stop_preview()
    camera.close()
def GetPhotos(counter = 0):
    """
    Photo aquisition
    """
    global filename
    
    debug("Camera init")
    try:
        camera = PiCamera()
    except picamera.exc.PiCameraMMALError:
        print "Camera crashed... calling again."
        GetPhotos(counter)
        return
    debug("Camera start")
    camera.start_preview()
    time.sleep(1)
    #if not os.path.exists(SAVEDIR):
    #    os.makedirs(SAVEDIR)
    year = time.strftime("%Y", time.localtime())
    month = time.strftime("%m", time.localtime())
    if not os.path.exists("%s/%s/%s" % (SAVEDIR, year, month)):
        os.makedirs("%s/%s/%s" % (SAVEDIR, year, month) )
    timestamp = time.strftime("%Y-%m-%d_%H%M%S", time.localtime())
    filename = "%s/%s/%s/%s-%04d.jpg" % (SAVEDIR, year, month, timestamp,counter)
    debug("Saving file %s" % filename)
    camera.capture(filename)
    camera.stop_preview()
    camera.close()
Exemplo n.º 27
0
class PiVideoStream:
    def __init__(self, resolution=(640, 480), framerate=48):
        # initialize the camera and stream
        self.camera = PiCamera()
        #self.camera.video_stabilization = True
        self.camera.resolution = resolution
        self.camera.framerate = framerate
        self.rawCapture = PiRGBArray(self.camera, size=resolution)
        self.stream = self.camera.capture_continuous(self.rawCapture,
            format="bgr", use_video_port=True)

        # initialize the frame and the variable used to indicate
        # if the thread should be stopped
        self.frame = None
        self.stopped = False

    def start(self):
        # start the thread to read frames from the video stream
        t = Thread(target=self.update, args=())
        t.daemon = True
        t.start()
        return self

    def update(self):
        # keep looping infinitely until the thread is stopped
        for f in self.stream:
            # grab the frame from the stream and clear the stream in
            # preparation for the next frame
            self.frame = f.array
            self.rawCapture.truncate(0)

            # if the thread indicator variable is set, stop the thread
            # and resource camera resources
            if self.stopped:
                self.stream.close()
                self.rawCapture.close()
                self.camera.close()
                return

    def read(self):
        # return the frame most recently read
        return self.frame

    def stop(self):
        # indicate that the thread should be stopped
        self.stopped = True
        
    # Settings for consistent images capture
    # Must be called some times after the camera is started
    def consistent(self):
        self.camera.shutter_speed = self.camera.exposure_speed
        self.camera.exposure_mode = 'off'
        g = self.camera.awb_gains
        self.camera.awb_mode = 'off'
        self.camera.awb_gains = g
Exemplo n.º 28
0
def capture_image():
    camera = PiCamera()
    camera.start_preview()
    sleep(3)
    camera.capture('/home/pi/kaffe.jpg')
    camera.stop_preview()
    camera.close()
Exemplo n.º 29
0
	def connect(self):
		sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

		server_address = (conf.ip, conf.videoport)

		sock.connect(server_address)

		# initialize the camera and grab a reference to the raw camera capture
		camera = PiCamera()
		camera.resolution = (640, 480)
		camera.framerate = 32
		rawCapture = PiRGBArray(camera, size=(640, 480))

		# allow the camera to warmup
		time.sleep(0.1)

		frm = 0

		# capture frames from the camera
		for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
			# grab the raw NumPy array representing the image, then initialize the timestamp
			# and occupied/unoccupied text
			image = frame.array

			gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

			gray = cv2.flip(gray,0)
			gray = cv2.flip(gray,1)

			frm = frm + 1
			if (frm >= 256):
			   frm = 0

			data = np.zeros((640), dtype=np.uint8)
			data[0] = data[1] = data[2] = data[3] = data[5] = 32
			sent = sock.sendto(data, server_address)

			# for i in range(1,480):
			#    data = gray[i,:]
			#    sent = sock.sendto(data, server_address)

			data = gray.reshape(640*480,1)
		   	sent = sock.sendto(data, server_address)


			#cv2.imshow("My Image", gray)

			if cv2.waitKey(1) & 0xFF == ord('q'):
			  break

			# clear the stream in preparation for the next frame
			rawCapture.truncate(0)

			if (self.keeprunning == False):
			  break
Exemplo n.º 30
0
def on_key_release(event):
    path = sys.path[0]
    cv2.putText(found, iso_str, (30, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.75, 255,
                2)
    cv2.putText(found, shutter_str, (300, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.75,
                255, 2)
    cv2.putText(found, awb_str, (30, 475), cv2.FONT_HERSHEY_SIMPLEX, 0.75, 255,
                2)
    cv2.imwrite(
        str(path) + "/" + strftime("%Y_%m_%d__%I_%M_%S", gmtime()) +
        "_test.jpg", found)
    print "Picture saved"


camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 30
camera.awb_mode = 'off'
#camera.awb_mode = 'sunlight'

aruco_dic = aruco.Dictionary_get(aruco.DICT_6X6_250)

master = Tk()
master.title("Adjust")

awbgain_r = Scale(master,
                  from_=0.1,
                  to=8,
                  orient=HORIZONTAL,
                  label='awb_gain red',
Exemplo n.º 31
0
 def __init__(self, server, resolution, framerate):
     PiCamera.__init__(self, resolution=resolution, framerate=framerate)
     self.server = server
     self.compid = None
     self.capturing = Event()
picam = False

if picam:
    from picamera import PiCamera
else:
    import cv2

import time
import telepot
import RPi.GPIO as GPIO
import subprocess

if picam:
    camera = PiCamera()
    camera.rotation = 180

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN)
intruder = False
enabled = False


def handle(msg):
    global enabled
    global intruder

    command = msg['text']
    from_id = msg['from']['id']
    #chat_id = msg['chat']['id']
    #print 'Got command: %s' % command
Exemplo n.º 33
0
def diff_avg(diff_frames, fs):
    means = []
    for i in range(
            1, len(diff_frames)):  # To remove diff of first frame with itself
        means.append(np.mean(diff_frames[i]))
    hamming_coeffs_resp = firwin(65, [0.05 / (fs / 2), 2.0 / (fs / 2)],
                                 pass_zero=False)  # Bandpass filter
    hamming = np.convolve(hamming_coeffs_resp, means, mode='same')

    return hamming


################################# Main ################################
# Picamera
camera = PiCamera(resolution=(640, 480), framerate=40)
fps = 5
stream = io.BytesIO()

frame_count = 0
diff_frames = []
sampling_freq = args.fs
sampling_num = fps / sampling_freq  # number of frames between the two frames used for diff calculation
samp_count = 0
pic_count = 0
time.sleep(0.1)
start = time.time()
flag = 0
for foo in camera.capture_continuous(stream, 'jpeg', use_video_port=True):
    frame = np.array(Image.open(stream))
    #     # VJ
client = None

if conf["use_dropbox"]:
	# connect to dropbox and start the session authorization process
	flow = DropboxOAuth2FlowNoRedirect(conf["dropbox_key"], conf["dropbox_secret"])
	print "[INFO] Authorize this application: {}".format(flow.start())
	authCode = raw_input("Enter auth code here: ").strip()
 
	# finish the authorization and grab the Dropbox client
	(accessToken, userID) = flow.finish(authCode)
	client = DropboxClient(accessToken)
	print "[SUCCESS] dropbox account linked"


# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = tuple(conf["resolution"])
camera.framerate = conf["fps"]
rawCapture = PiRGBArray(camera, size=tuple(conf["resolution"]))
 
# allow the camera to warmup, then initialize the average frame, last
# uploaded timestamp, and frame motion counter
print "[INFO] warming up..."
time.sleep(conf["camera_warmup_time"])
avg = None
lastUploaded = datetime.datetime.now()
motionCounter = 0

# capture frames from the camera
for f in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
	# grab the raw NumPy array representing the image and initialize
Exemplo n.º 35
0
def measureCamera():
        # initialize the camera and grab a reference to the raw camera capture
        camera = PiCamera()
        camera.resolution = (320, 240)
        camera.framerate = 10
        camera.awb_mode='off'
        camera.shutter_speed=5000*4
        camera.awb_gains=awb_gains_default
        rawCapture = PiRGBArray(camera, size=(320, 240))

        # allow the camera to warmup
        time.sleep(0.1)

        tubo_inserido=False
        amostra_detectada=False
        baricentro_y_ant=-1
        a=0
        v_min_ant=100
        time_c=0
        counter=0
        def captura(luz):
            gpio.output(gpioW1,gpio.LOW)
            gpio.output(gpioW2,gpio.LOW)
            gpio.output(gpioR,gpio.LOW)
            gpio.output(gpioG,gpio.LOW)
            if(luz=='R'):
                gpio.output(gpioR,gpio.HIGH)
                awbgains=(65/128,175/64)
            elif(luz=='G'):
                gpio.output(gpioG,gpio.HIGH)
                awbgains=(417/256,449/256)
            else:
                awbgains=(417/256,449/256)
                gpio.output(gpioW2,gpio.HIGH)
            camera.shutter_speed=5284*4
            camera.iso=10
            camera.awb_gains=awbgains
            time.sleep(0.1)
            raw_output = PiRGBArray(camera)
            camera.capture(raw_output, 'bgr')
            """print(camera.awb_gains)
            print(camera.analog_gain)
            print(camera.digital_gain)"""
            output=raw_output.array
            return output
        # capture frames from the camera
        for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
            # grab the raw NumPy array representing the image, then initialize the timestamp
            # and occupied/unoccupied text
            image = frame.array 
            crop=image[35:196,153:153+16]
            
            #converte no espaco hsv
            hsv = cv2.cvtColor(crop, cv2.COLOR_BGR2HSV)

            count_amostra=0
            baricentro_y=0
            baricentro_x=0
            points=0
            average_brightness=0
            v_min=100
            for i in range(0,len(crop)):
                for j in range(0,len(crop[0])):
                    h=hsv[i][j][0]*360/179
                    s=hsv[i][j][1]*100/255
                    v=hsv[i][j][2]*100/255
                    if(i>70 and j>5 and j<9):
                        if(v<v_min):
                            v_min=v
                    #se nao for escuro
                    if(h<40 or h>340):
                        if(s>50):
                            #se saturacao eh maior q um valor, isto e, se for colorido, eh amostra
                            amostra=True
                            
                        else:
                            amostra=False
                    else:
                        amostra=False
                    
                    #conta os pixels por linha q eh de amostra
                    if(amostra):
                        count_amostra+=1
                        baricentro_x+=j
                        baricentro_y+=i
                        
            if(count_amostra==0):
                amostra_detectada=False
                baricentro_y=-1    
            else:
                baricentro_x=baricentro_x/count_amostra
                baricentro_y=baricentro_y/count_amostra
                if(abs(baricentro_y_ant-baricentro_y)<2 and baricentro_y>0):
                    amostra_detectada=True
                baricentro_y_ant=baricentro_y 
            
            if(time_c>=2):
                time_c=0
                tubo_inserido=v_min_ant<90 and v_min<90
                v_min_ant=v_min
            else:
                time_c+=1
                
            
            if(tubo_inserido):
                if(status!='medido'):
                    if(amostra_detectada):
                        if(baricentro_x>4 and baricentro_x<12):
                            status='medicao'
                        else:
                            status='ajuste'
                    else:
                        status='invertido'
            else:
                status='inicial'
                
            changeStatus(status)
            if(status=='medicao'):
                outputW=captura('W')
                outputR=captura('R')
                outputG=captura('G')
                gpio.output(gpioW1,gpio.HIGH)
                gpio.output(gpioW2,gpio.LOW)
                gpio.output(gpioR,gpio.LOW)
                gpio.output(gpioG,gpio.LOW)
                crop=outputW[35:196,153:153+16]
                cropR=outputR[35:196,153:153+16]
                cropG=outputG[35:196,153:153+16]

                process=np.zeros((len(crop),len(crop[0]),3)).astype(np.uint8)
            
                hsv = cv2.cvtColor(crop, cv2.COLOR_BGR2HSV)

                #1 filtragem: verifica saturacao
                start_success=-1
                success_sum=0
                factor=0.2
                last_row=0
                for i in range(0,len(crop)):
                    success=0
                    for j in range(0,len(crop[0])):
                        h=hsv[i][j][0]*360/179
                        s=hsv[i][j][1]*100/255
                        v=hsv[i][j][2]*100/255
                        #se matiz esta dentro do vermelho/laranja
                        if(h<35 or h>345):
                            if(s>45):
                                #se saturacao eh maior q um valor, isto e, se for colorido, eh amostra
                                amostra=True
                            else:
                                amostra=False
                        else:
                            amostra=False
                        #conta os pixels por linha q eh de amostra
                        if(amostra):
                            success+=1
                            process[i][j]=hsv[i][j]
                    last_row=i

                    #2 filtragem para descartar os blocos nao conectados
                    if(success>0 and start_success==-1):
                        start_success=i
                    if(start_success>=0):
                        success_sum+=success
                        success_average=success_sum/(i-start_success+1)
                        if(success<factor*success_average and (i-start_success)>10 and success_average>5):
                            process[i]=np.zeros((1,len(crop[0]),3)).astype(np.uint8)
                            break
                color_count=0
                W_average=(0,0,0)
                R_average=(0,0,0)
                G_average=(0,0,0)
                for i in range(0,last_row+1):
                    for j in range(0,len(process[0])):
                        if(not np.array_equal(process[i][j],[0,0,0])):
                            W_average+=crop[i][j]
                            R_average+=cropR[i][j]
                            G_average+=cropG[i][j]
                            color_count+=1
                            
                if(color_count!=0):
                   W_average=W_average/color_count
                   R_average=R_average/color_count
                   G_average=G_average/color_count
                print(W_average)
                fileW.write(str(W_average)+'\n')
                fileR.write(str(R_average)+'\n')
                fileG.write(str(G_average)+'\n')
                
                #funcao da rede neural
                indice=W_average[1]
                
                cv2.imwrite('imageW'+str(counter)+'.png',outputW)
                cv2.imwrite('imageR'+str(counter)+'.png',outputR)
                cv2.imwrite('imageG'+str(counter)+'.png',outputG)
                counter+=1
                
                status='medido'
                changeStatus(status)
                camera.shutter_speed=5000*4
                camera.awb_gains=awb_gains_default
            
           # show the frame
            print(status)
            key=cv2.waitKey(1)&0xFF

            # clear the stream in preparation for the next frame
            rawCapture.truncate(0)

            # if the `q` key was pressed, break from the loop
            if key == ord("q"):
                fileW.close()
                fileG.close()
                fileR.close()
                break
Exemplo n.º 36
0
from picamera import PiCamera
from datetime import datetime
import RPi.GPIO as GPIO
import smbus
import time 
from time import sleep

port = 1
bus = smbus.SMBus(port)

apds = APDS9960(bus)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.IN)
GPIO.setup(38, GPIO.OUT)

camera = PiCamera()
cameraFlag = 0

#define callbacks
def intH(channel):
    print("take picture")

#def cameraFlash(channel):
#    print("make flash")
#    GPIO.output(38,GPIO.HIGH)

try:
    #interrupt event-driven
    GPIO.add_event_detect(7, GPIO.FALLING, callback = intH)
    apds.setProximityIntLowThreshold(50)
    
Exemplo n.º 37
0
    RECORDING = True  # set recording flag
    return


def stop_record():
    camera.stop_recording()  #stop recording
    RECORDING = False
    return


try:
    print("PIR Module Test started")
    start_time = time.time()
    time.sleep(1)
    count = 0
    camera = PiCamera()

    while True:
        inputTrigger = GPIO.input(PIR_PIN)
        if (inputTrigger and not RECORDING):
            count = count + 1  #increase total motion count
            print("Motion Detected!"
                  )  #print motion detection, later will want to log it
            start_record()  #record motion!
        time.sleep(2)  # loop delay in seconds - smooth out sensor readings
        if (not inputTrigger and RECORDING):
            stop_record()
except KeyboardInterrupt:
    print("...Program Interrupt")
    print("Total Motion Count: " + str(count))
    print("Elapsed Time: " + str(time.time() - start_time))
Exemplo n.º 38
0
lenreg = length / 4
failCounter = 0

print("running {} cycles on all pins".format(cycles))

input = raw_input("run y/n")
if input == "y":
    run = 0
    wiringpi.digitalWrite(17, 0)
    wiringpi.digitalWrite(27, 0)
    wiringpi.digitalWrite(22, 0)
    wiringpi.digitalWrite(5, 0)
    wiringpi.digitalWrite(6, 0)
    print("running {} cycles on all pins".format(cycles))

with camera as PiCamera():
    camera.resolution = (width, length)
    camera.framerate = 20
    rawCapture = PiRGBArray(camera, size=(width, length))

    startCase = np.empty((width, length, 3), dtype=np.uint32)
    endCase = np.empty((width, length, 3), dtype=np.uint32)
    delta = []
    time.sleep(0.1)
    roi1 = []
    roi2 = []
    roi3 = []
    roi4 = []
    roi5 = []

    camera.start_recording(test.h264)
Exemplo n.º 39
0
import cv2
import time
from picamera.array import PiRGBArray
from picamera import PiCamera
#в строках 1-4 мы пдключаем библиотеки
print("enter name of file")
name=int(input())
print("enter the period of observation (second)")
period=int(input())
print("enter the videoTime (second)")
videoTime=int(input())
#в строках 6-11 вводим переменные для настройки времени работы


camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 24
raw = PiRGBArray(camera)
time.sleep(0.1)
#в строках 15-19 подключаем камеру для RPi 


fourcc = cv2.VideoWriter_fourcc(*'XVID')
vid = cv2.VideoWriter(name+'.avi',fourcc, 24.0, (640,480))
#в строках 23-24 настраиваем видеовыход


if(period<videoTime):
    print("error! videoTime > period")
    exit()
#в строках 28-30 проверяем правильность введенных переменных
Exemplo n.º 40
0
import sys
from twython import Twython
from picamera import PiCamera
from time import sleep

apiKey = "sQQEszZ8Gwy8SVnZeeuLMF40C"
apiSecret = "GWdTgpS7p9t6P7ZCC3QdRFTMBl75NyTVQwodz20sOIV85n7ooo"
accessToken = "1271178365219766272-R5eAnVIeIRDFdlYpp7namiweyFk3Zp"
accessTokenSecret = "1XxHeiD9vL851hbbuuXoJHMuCTvPEqymbdtYCopQ1UxdG"

api = Twython(apiKey, apiSecret, accessToken, accessTokenSecret)

camera = PiCamera()

for i in range(5):
    camera.start_preview()
    sleep(5)
    camera.capture('./image{}.jpg'.format(i))
    camera.stop_preview()
    sleep(5)
    photo = open('./image{}.jpg'.format(i), 'rb')
    response = api.upload_media(media=photo)
    api.update_status(status="Image{} from Raspberry Pi Camera".format(i),
                      media_ids=[response['media_id']])
Exemplo n.º 41
0
tilt_pin = 5
tilt_MAXDUTY = 9.5
tilt_MINDUTY = 3.5

GPIO.setmode(GPIO.BCM)

GPIO.setup(pan_pin, GPIO.OUT)
pan = GPIO.PWM(pan_pin, 50)
pan.start(7.5)

GPIO.setup(tilt_pin, GPIO.OUT)
tilt = GPIO.PWM(tilt_pin, 50)
tilt.start(7.5)

camera = PiCamera()
camera.resolution = (160, 128)
camera.framerate = 40
rawCapture = PiRGBArray(camera, size=(160, 128))

time.sleep(0.1)

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

for frame in camera.capture_continuous(rawCapture,
                                       format='bgr',
                                       use_video_port=True):
    img = frame.array
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in faces:
Exemplo n.º 42
0
def socket_send(sock, data):
    if data == None:
        return
    sock.send( str(data.shape[0]).ljust(16).encode() );
    sock.send( data );

#연결할 서버(수신단)의 ip주소와 port번호
TCP_IP = '192.168.0.7'
TCP_PORT = 5001
CAM_WIDTH = 320
CAM_HEIGHT = 240

#송신을 위한 socket 준비
print("Getting ready for camera ...")
camera = PiCamera()
camera.resolution = (CAM_WIDTH, CAM_HEIGHT)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(CAM_WIDTH, CAM_HEIGHT))

time.sleep(0.1)

print("Connecting to the server ...")
while(True):
    try:
        sock = socket.socket()
        sock.connect((TCP_IP, TCP_PORT))
        break
    except:
        continue
    #else:
    #    global overlay # http://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists
    #    overlay = next(all_overlays)# http://stackoverflow.com/questions/26545051/is-there-a-way-to-delete-created-variables-functions-etc-from-the-memory-of-th
    #preview_overlay(camera, overlay)


# Tell the take picture button what to do
def take_picture():
    camera.capture(output)
    camera.stop_preview()


# Set up buttons
next_overlay_btn = Button(23)
next_overlay_btn.when_pressed = next_overlay
take_pic_btn = Button(25)
take_pic_btn.when_pressed = take_picture

# Set up camera (with resolution of the touchscreen)
camera = PiCamera()
camera.resolution = (800, 480)
camera.hflip = True

# Start camera preview (delete alpha=128 once you know your code works)
camera.start_preview(alpha=128)

# Set up filename
output = strftime(
    "/home/pi/photobooth/tests/allseeingpi_test/image-%d-%m %H:%M.png",
    gmtime())
Exemplo n.º 44
0
from picamera import PiCamera, Color
from time import sleep

camera = PiCamera()  # PiCamera객체 생성
camera.rotation = 180
camera.start_preview()  # 미리보기 화면을 시작

#동영상 저장 시작
camera.start_recording("/home/pi/iot/video.h264")
sleep(10)
camera.stop_recording()
camera.stop_preview()  # 미리보기 화면 정지
# import the necessary packages
from imutils import contours
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import serial
import numpy as np
import imutils
import cv2

# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (512, 512)
camera.framerate = 25
rawCapture = PiRGBArray(camera, size=(512, 512))

# allow the camera to warmup
time.sleep(0.1)

ser = serial.Serial('/dev/ttyUSB0',9600)

shape_C = 0
shape_R = 0
shape_D = 0

while True : 
    while True :
        read_serial=ser.readline()
        read_serial_num = int (read_serial, 10)
        if read_serial_num == 1:
            break
Exemplo n.º 46
0
from io import BytesIO
from time import sleep

from picamera import PiCamera
import numpy
import scipy
from PIL import Image


camera = PiCamera()
#camera.start_preview()
#sleep(1)
camera.color_effects = (128, 128)

for res in [1024]:

    imgID = 0
    camera.resolution = (800, 600)

    for repo in range(5):
        stream = BytesIO()
        camera.capture(stream, 'png')
        stream.seek(0)

        #with open("./testimgs/test.{}.{}.png".format(res,imgID), "wb") as fout:
        #    fout.write(stream.read())
        imgID += 1
        #stream.flush()
        print("ready...")
        #sleep(2)
Exemplo n.º 47
0
class My_Cam:
    def __init__(self, pserve, clothes, playvid, appdirs, config, logger):
        self._pv = playvid
        self._cfg = config
        self._log = logger
        self._appdir = appdirs

        self.clothes = clothes
        self.pserve = pserve

    def start(self):

        self.cam = PiCamera()

        # self.cam.led = False
        self.cam.framerate = 24

        self.cam.hflip = True

        # Camera Controls
        self.cam.rotation = self._cfg.getint("PI CAMERA", "rotation")  #90
        #cam.resolution = (640, 1024)

        self.cam.contrast = self._cfg.getint("PI CAMERA",
                                             "contrast")  #100 # Range -100 100
        #cam.saturation = 100 # Range -100 100
        self.cam.brightness = self._cfg.getint("PI CAMERA",
                                               "brightness")  # 80 # 0 100
        #cam.awb_mode = "shade"

        self.cam.iso = self._cfg.getint("PI CAMERA", "iso")  # 1600

        self.cam.sensor_mode = self._cfg.getint("PI CAMERA",
                                                "sensor_mode")  # 1

        self.cam.shutter_speed = 1 / self._cfg.getint("PI CAMERA",
                                                      "shutter_speed")

        # Preview window
        self.x = self._cfg.getint("PI CAMERA", "x")
        self.y = self._cfg.getint("PI CAMERA", "y")
        self.w = self._cfg.getint("PI CAMERA", "width")
        self.h = self._cfg.getint("PI CAMERA", "height")

    def turn_on(self):
        self.start()
        self.pserve.send("m_camera", "cam_on")

        self._log.info("warming camera up")
        self.cam.start_preview(fullscreen=False,
                               window=(self.x, self.y, self.w, self.h))
        self.pserve.send("m_camera", "preview_on")

    def turn_off(self):
        # Stop Preview Video
        self.quit()

        # Stop Camera Preview
        self.cam.stop_preview()
        self.pserve.send("m_camera", "preview_off")

        # Close off camera class
        self.cam.close()
        self.pserve.send("m_camera", "cam_off")

    def quit(self):
        self._pv.stop_auto()

    def rec_start(self):
        self.t = str(int(time()))

        # Campure thumbnail
        self._log.info("Capturing thumbnail")
        self.cam.capture('%s/cls/%s.jpg' % (
            self._appdir,
            self.t,
        ))

        # Compress image
        cmp_im = Image.open('%s/cls/%s.jpg' % (
            self._appdir,
            self.t,
        ))
        cmp_im.save('%s/cls/%s.jpg' % (
            self._appdir,
            self.t,
        ),
                    optimize=True,
                    quality=20)

        self.pserve.send("m_camera", "thumb_captured")

        self._log.info("Recording video")
        self.pserve.send("m_camera", "video_start")
        self.cam.start_recording("%s/cls/%s.h264" % (
            self._appdir,
            self.t,
        ))

    def rec_stop(self):

        self.cam.stop_recording()
        self._log.info("Recording stopped")
        self.pserve.send("m_camera", "video_end")

        # Compress video
        self.pserve.send("m_camera", "compression_begin")
        call("MP4Box -add %s/cls/%s.h264 %s/cls/%s.mp4" % (
            self._appdir,
            self.t,
            self._appdir,
            self.t,
        ),
             shell=True)
        self.pserve.send("m_camera", "compression_off")

        os.remove("%s/cls/%s.h264" % (
            self._appdir,
            self.t,
        ))

        self.pserve.send("m_camera", "getting_dresscode")
        cl = self.clothes.add("casual", self.t + ".jpg")
        self.pserve.send("m_camera_dat", json.dumps(cl))

        self._log.info("Camera stop")
        self.cam.stop_preview()

        try:
            self._pv.add_size()
            thread.start_new_thread(self._pv.play_auto, (cl[0]["id"], ))
        except:
            self._log.error("Playing video failed")

        return cl
Exemplo n.º 48
0
import RPi.GPIO as GPIO
from time import sleep
import schedule
import time
from camera_google import googleCamera
from camera_file import dir_entries
from picamera import PiCamera
from datetime import datetime

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

camera = PiCamera()
camera.resolution = (640, 480)

buzz = 2
button = 27
recording = False

GPIO.setup(buzz, GPIO.OUT)
GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP)


def cam_record():

    timestamp = datetime.now().isoformat()

    camera.annotate_text = timestamp
    camera.annotate_text_size = 50
    #camera.annotate_foreground = Color("yellow")
Exemplo n.º 49
0
# For testing
# Replace libraries by fake ones
import sys
import fake_rpi

sys.modules['picamera'] = fake_rpi.picamera     # Fake picamera

from time import sleep
from picamera import PiCamera
import pickle
import cv2 as cv
from tkinter import Tk
from tkinter.filedialog import askopenfilename

camera = PiCamera()
camera.resolution = (1024, 768)

camera.start_preview()
sleep(10)
camera.capture('foo.jpg')
camera.stop_preview()

# Load calibration
print('Choose the calibration .pkl file.')
Tk().withdraw()
cal_file = askopenfilename()

F = open(cal_file, 'rb')
ret = pickle.load(F)
mtx = pickle.load(F)
dist = pickle.load(F)
Exemplo n.º 50
0
def get_cv():

    global w
    global h

    # for i in range(5):
    # GPIO.output(CAMLED,True) # On
    # time.sleep(0.5)
    # GPIO.output(CAMLED,False) # Off
    # time.sleep(0.5)

    camera = PiCamera()
    camera.close()
    camera = PiCamera()
    rawCapture = PiRGBArray(camera)
    rawCapture2 = PiRGBArray(camera)

    # Turn the camera's LED off
    camera.led = False
    w = 800
    h = 600
    camera.resolution = (w, h)
    # Take a picture while the LED remains off

    time.sleep(.2)

    # camera.iso = 400

    camera.contrast = 100

    # camera = PiCamera(resolution=(1280, 720), framerate=30)
    # Set ISO to the desired value

    # Wait for the automatic gain control to settle
    #time.sleep(4)
    # Now fix the values
    camera.shutter_speed = camera.exposure_speed
    s = camera.shutter_speed
    if s < 10000:
        camera.iso = 600
    ciso = camera.iso
    camera.exposure_mode = 'off'
    g = camera.awb_gains
    camera.awb_mode = 'off'
    camera.awb_gains = g
    # Finally, take several photos with the fixed settings
    #camera.capture_sequence(['image%02d.jpg' % i for i in range(10)])
    camera.capture(rawCapture, format="bgr")
    picam_01 = rawCapture.array
    time.sleep(1)

    GPIO.output(CAMLED, True)  # On
    time.sleep(1)

    camera.capture(rawCapture2, format="bgr")
    picam_02 = rawCapture2.array
    #camera.capture(rawCapture, format="bgr")
    #picam_01 = rawCapture.array
    #time.sleep(.1)
    #GPIO.output(CAMLED,True) # On
    #time.sleep(10)
    #GPIO.output(CAMLED,True) # On
    #camera.capture(rawCapture2, format="bgr")
    #picam_02 = rawCapture2.array
    time.sleep(2)
    GPIO.output(CAMLED, False)  # Off

    crop_img = picam_02[(h / 5.33):(h / 1.23), (w / 24):(
        w / 1.04)].copy()  # Crop from x, y, w, h -> 100, 200, 300, 400

    crop_img2 = picam_01[(h / 5.33):(h / 1.23), (w / 24):(
        w / 1.04)].copy()  # Crop from x, y, w, h -> 100, 200, 300, 400

    #gray = cv2.cvtColor(crop_img,cv2.COLOR_BGR2GRAY)
    #gray2 = cv2.cvtColor(crop_img2,cv2.COLOR_BGR2GRAY)

    cv2.imwrite("g1.jpg", crop_img)
    cv2.imwrite("g2.jpg", crop_img2)

    diff = cv2.absdiff(crop_img, crop_img2)

    camera.close()

    # CLAHE (Contrast Limited Adaptive Histogram Equalization)
    clahe = cv2.createCLAHE(clipLimit=3., tileGridSize=(8, 8))
    lab = cv2.cvtColor(
        diff, cv2.COLOR_BGR2LAB)  # convert from BGR to LAB color space
    l, a, b = cv2.split(lab)  # split on 3 different channels
    l2 = clahe.apply(l)  # apply CLAHE to the L-channel
    lab = cv2.merge((l2, a, b))  # merge channels
    img2 = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)  # convert from LAB to BGR
    cv2.imwrite('sunset_modified.jpg', img2)

    gray = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)

    #blur2 = cv2.GaussianBlur(diff,(15,15),0)

    #ret,thresh2 = cv2.threshold(blur2, 6,255,cv2.THRESH_BINARY_INV)

    #cv2.imwrite( "gray.jpg", gray )

    #blur = cv2.bilateralFilter(gray,6,12,3)
    img_hsv = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)
    lower_red = np.array([0, 20, 20])
    upper_red = np.array([20, 255, 255])
    mask0 = cv2.inRange(img_hsv, lower_red, upper_red)

    # upper mask (170-180)
    lower_red = np.array([160, 20, 20])
    upper_red = np.array([180, 255, 255])
    mask1 = cv2.inRange(img_hsv, lower_red, upper_red)

    # join my masks
    mask = mask0 + mask1

    cv2.imwrite("mask.jpg", mask)

    blur = cv2.GaussianBlur(gray, (15, 15), 4)

    ret3, th3 = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY_INV)
    cv2.imwrite("blur.jpg", blur)

    edges = cv2.Canny(th3, 8, 24, 3)  #working
    cv2.imwrite("edges.jpg", edges)

    cv2.imwrite("th3.jpg", th3)

    lines = cv2.HoughLines(edges, 1, np.pi / 180, 50)

    data = []

    counter = 0
    rho_all = 0
    course = 200
    overlay = crop_img.copy()
    overlay2 = crop_img.copy()

    if lines is not None:
        for rho, theta in lines[0]:
            course = 0
            a = np.cos(theta)
            b = np.sin(theta)
            x0 = a * rho
            y0 = b * rho
            x1 = int(x0 + 1000 * (-b))
            y1 = int(y0 + 1000 * (a))
            x2 = int(x0 - 1000 * (-b))
            y2 = int(y0 - 1000 * (a))
            #data.insert(0,[rho,theta])
            data.insert(0, [theta, rho])
            if theta > ((np.pi / 4) * 3) or theta < (np.pi / 4):
                counter = counter + 1
                #cv2.line(crop_img,(x1,y1),(x2,y2),(0,255,10),2)
                temp = theta * (180 / np.pi)
                if temp > 90:
                    temp = temp - 180
                #data.insert(0,[theta,rho])

                rho_all = rho_all + temp

                # if counter < 10:
                # cv2.putText(crop_img, str(theta) ,(10,73+counter*30), cv2.FONT_HERSHEY_SIMPLEX, .4,(0,0,255),2)
                # if counter>9 and counter < 20:
                # cv2.putText(crop_img, str(theta) ,(100,73+(counter-10)*30), cv2.FONT_HERSHEY_SIMPLEX, .4,(0,0,255),2)#
                # if counter>19 and counter < 30:
                # cv2.putText(crop_img, str(theta) ,(200,73+(counter-20)*30), cv2.FONT_HERSHEY_SIMPLEX, .4,(0,0,255),2)
                # if counter>29 and counter < 40:
                # cv2.putText(crop_img, str(theta) ,(300,73+(counter-20)*30), cv2.FONT_HERSHEY_SIMPLEX, .4,(0,0,255),2)
                # if counter>39 and counter < 50:
                # cv2.putText(crop_img, str(theta) ,(400,73+(counter-20)*30), cv2.FONT_HERSHEY_SIMPLEX, .4,(0,0,255),2)
            else:
                #cv2.line(overlay,(x1,y1),(x2,y2),(255,10,10),2)
                a = "oli"

        # data1=(set(data))
        # print data1
        # cl = HierarchicalClustering(data1, lambda x,y: abs(x-y))
        # data2 = cl.getlevel(8)
        # print data2

        # flattened_list = []
        # for x in data2:
        # check=0
        # for y in x:
        # check=check+y
        # checksum=check/len(x)
        # flattened_list.append(checksum)

        # print flattened_list
        print data
        kmeans = KMeans(n_clusters=2, random_state=0, max_iter=3000).fit(data)
        print kmeans.cluster_centers_

        for rho, theta in lines[0]:

            a = np.cos(theta)
            b = np.sin(theta)
            x0 = a * rho
            y0 = b * rho
            x1 = int(x0 + 1000 * (-b))
            y1 = int(y0 + 1000 * (a))
            x2 = int(x0 - 1000 * (-b))
            y2 = int(y0 - 1000 * (a))

            if (kmeans.predict([theta, rho])) == 0:
                cv2.line(overlay, (x1, y1), (x2, y2), (255, 10, 255), 2)
            else:
                cv2.line(overlay, (x1, y1), (x2, y2), (255, 50, 10), 2)

        opacity = .3
        cv2.addWeighted(overlay, opacity, crop_img, 1 - opacity, 0, crop_img)

        ta = np.cos(kmeans.cluster_centers_[0][0])
        tb = np.sin(kmeans.cluster_centers_[0][0])
        tx0 = ta * kmeans.cluster_centers_[0][1]
        ty0 = tb * kmeans.cluster_centers_[0][1]
        tx1 = int(tx0 + 1000 * (-tb))
        ty1 = int(ty0 + 1000 * (ta))
        tx2 = int(tx0 - 1000 * (-tb))
        ty2 = int(ty0 - 1000 * (ta))
        cv2.putText(crop_img,
                    str(kmeans.cluster_centers_[0][0] * (180 / np.pi)),
                    (30, 190), cv2.FONT_HERSHEY_SIMPLEX, .4, (0, 0, 255), 2)
        cv2.line(crop_img, (tx1, ty1), (tx2, ty2), (255, 0, 0), 2)
        ta = np.cos(kmeans.cluster_centers_[1][0])
        tb = np.sin(kmeans.cluster_centers_[1][0])
        tx0 = ta * kmeans.cluster_centers_[1][1]
        ty0 = tb * kmeans.cluster_centers_[1][1]
        tx1 = int(tx0 + 1000 * (-tb))
        ty1 = int(ty0 + 1000 * (ta))
        tx2 = int(tx0 - 1000 * (-tb))
        ty2 = int(ty0 - 1000 * (ta))
        cv2.line(crop_img, (tx1, ty1), (tx2, ty2), (255, 0, 255), 2)
        cv2.putText(crop_img,
                    str(kmeans.cluster_centers_[1][0] * (180 / np.pi)),
                    (300, 190), cv2.FONT_HERSHEY_SIMPLEX, .4, (0, 0, 255), 2)
        #opacity = 1
        #cv2.addWeighted(overlay2, opacity, crop_img, 1 - opacity, 0, crop_img)

        #bandwidth = estimate_bandwidth(lines, quantile=0.2, n_samples=500)
        #print lines
        #X = StandardScaler().fit_transform(lines)
        #print X
        #bandwidth = estimate_bandwidth(data2, quantile=0.2, n_samples=len(data2))
        #print bandwith
        # ms = MeanShift()

        # ms.fit(data2)
        # labels = ms.labels_
        # cluster_centers = ms.cluster_centers_

        # labels_unique = np.unique(labels)
        # n_clusters_ = len(labels_unique)

        # print("number of estimated clusters : %d" % n_clusters_)

        if counter > 0:
            rho_all = rho_all / counter

            course = rho_all

            #if course>90:
            #course=course-180
        else:
            course = 200
        cv2.putText(crop_img, str(rho_all), (200, 13),
                    cv2.FONT_HERSHEY_SIMPLEX, .5, (0, 0, 255), 2)
        #cv2.putText(crop_img, str(course) ,(10,13), cv2.FONT_HERSHEY_SIMPLEX, .5,(0,0,255),2)
        cv2.putText(crop_img, str(g), (10, 33), cv2.FONT_HERSHEY_SIMPLEX, .5,
                    (0, 0, 255), 2)
        cv2.putText(crop_img, str(s), (10, 53), cv2.FONT_HERSHEY_SIMPLEX, .5,
                    (0, 0, 255), 2)

    now = datetime.datetime.now()
    filename = "pictures/"
    filename += str(now.microsecond)
    filename += ".jpg"

    filename2 = "<img src=\""
    filename2 += filename
    filename2 += "\" alt=\"Fehler beim anzeigen\" />,"

    cv2.imwrite(filename, crop_img)

    test_results = {
        'shutter_speed': str(s),
        'awb_gain': str(g),
        'course': str(course),
        'img': filename2,
        'iso': str(ciso),
    }
    # dict of colors for each result:
    result_colors = {
        'success': 'lime',
        'failure': 'red',
        'error': 'yellow',
    }
    t = HTML.Table(header_row=['Test', 'Result'])
    for test_id in sorted(test_results):
        # create the colored cell:
        #color = result_colors[test_results[test_id]]
        colored_result = HTML.TableCell(test_results[test_id], 'white')
        # append the row with two cells:
        t.rows.append([test_id, colored_result])
    htmlcode = str(t)

    f = open('report2.html', 'a+')
    f.write(htmlcode)
    f.close()

    return course
Exemplo n.º 51
0
import time
from picamera.array import PiRGBArray
from picamera import PiCamera
import cv2
import numpy as np
import Adafruit_PCA9685
from threading import Thread
from flask import Blueprint, jsonify, Response

#Get the picture (low resolution, so it should be quite fast)
#Here you can also specify other parameters (e.g.:rotate the image)

pwm = Adafruit_PCA9685.PCA9685()
camera = PiCamera()

## CONSTANTS ##

HEIGHT = 480
WIDTH = 640

SCALE_FACTOR = 0.25

SCALED_WIDTH = int(WIDTH * SCALE_FACTOR)
SCALED_HEIGHT = int(HEIGHT * SCALE_FACTOR)

SCALED_X_CENTER = int(SCALED_WIDTH / 2)
SCALED_Y_CENTER = int(SCALED_HEIGHT / 2)

HORIZ_LINE_WIDTH = (WIDTH * .75)

ESC_PIN = 1
import cv2
import numpy as np
from picamera import PiCamera
import time

camera = PiCamera()
camera.capture('capture6.jpg')

img1 = cv2.imread('timcup.png', 0)
img2 = cv2.imread('capture6.jpg', 0)

ret, thresh = cv2.threshold(img1, 127, 255, 0)
ret, thresh2 = cv2.threshold(img2, 127, 255, 0)
contours, hierarchy = cv2.findContours(thresh, 2, 1)
cnt1 = contours[0]
contours, hierarchy = cv2.findContours(thresh2, 2, 1)
cnt2 = contours[0]

#print "cnt1 " + str(cnt1)
#print "cnt2 " + str(cnt2)

ret = cv2.matchShapes(cnt1, cnt2, 1, 0.0)
print ret
Exemplo n.º 53
0
from time import sleep, strftime, time # for the picamera and to name the files
from datetime import datetime, timedelta       # possbily not needed but used to get the sunrise for today
from config import *    # my dropbox API key and Push bullet API key

from picamera import PiCamera # raspberry pi camera

import sys

from PIL import Image #python3 -m pip install Pillow, also need: sudo apt-get install libopenjp2-7, sudo apt install libtiff5

from pushbullet import Pushbullet   # notification software to monitor the programme remotely `pip3 install pushbullet.py`
pb = Pushbullet(PUSHBULLET)

# the Picamera
camera = PiCamera()
camera.resolution = (3280, 2464)

def lapse_details(duration_in_minutes, fps):
    print(f"User lapse duration request: {duration_in_minutes} minutes.")
    real_time = duration_in_minutes * 60 # minutes * 60 seconds
    film_length = 30
    frame_rate = fps
    total_frames = film_length * frame_rate
    delay = real_time / total_frames
    return total_frames, delay

def the_camera(no_of_frames, delay):
    start_time = strftime("%H:%M:%S")
    print(f"The camera BEGAN taking images at {start_time}")
    camera.start_preview()
    sleep(2) # Camera warm-up time
Exemplo n.º 54
0
# Watch a 10 second stream from camera

from picamera import PiCamera
from time import sleep

camera = PiCamera()

camera.start_preview(alpha=200) # Set the transparency of the camera alpha, can be any value between 0 and 255
sleep(10)
camera.stop_preview()
Exemplo n.º 55
0
from picamera.array import PiRGBArray
from picamera import PiCamera
import numpy as np
import time
import cv2

# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 30
rawCapture = PiRGBArray(camera, size=camera.resolution)

opciones = 2

DP = 2
MIN_DIST = 1080
PARAM1 = 120
PARAM2 = 50
MIN_RADIO = 10
MAX_RADIO = 0
TAM_KERNEL = 6
KERNEL = np.ones((TAM_KERNEL, TAM_KERNEL), np.uint8)
ITER_ERODE = 2
ITER_DILATE = 10

if opciones == 1:  # Cuarto viendo hacia el closet
    minYellowHsv = [22, 40, 45]
    maxYellowHsv = [47, 140, 255]

if opciones == 2:  # Mesitaimport cv2 viendo hacia la pared con lucesw prendidas
    minYellowHsv = [30, 65, 90]
Exemplo n.º 56
0
    # goleft : 左折
    # goright : 右折
    # back : まっすぐ後進
    # backleft : 左へ後進
    # backright : 右へ後進
    # break : ブレーキ
    order = param[1]

    # GPIO端子の設定
    motor1_pin = 23
    motor2_pin = 24

    wiringpi.wiringPiSetupGpio()
    wiringpi.pinMode(motor1_pin, 1)
    wiringpi.pinMode(motor2_pin, 1)

    # カメラの初期化(必ず関数の外側で!!!)
    my_camera = PiCamera()
    my_camera.resolution = (320, 240)
    my_camera.framerate = 32
    rawCapture = PiRGBArray(my_camera, size=(320, 240))

    # ラップトップがあるかどうかのフラグ
    not_exist = True
    stop_item = 'notebook'

    th1 = threading.Thread(target=camera, name="th", args=())
    # th2 = threading.Thread(target=motor, name="th", args=())

    th1.start()
    # th2.start()
Exemplo n.º 57
0
def catchStone(workState):
    workState.put(0)
    workState.task_done()

    #set camera
    camera = PiCamera(resolution=(1920, 1080))
    camera.shutter_speed = int(config['camera']['shutter_speed'])
    sleep(1)
    camera.capture(original_img)
    workState.put(1)
    workState.task_done()
    camera.close()

    # Read image
    img = cv2.imread(original_img)

    #crop image
    x = 284
    y = 23
    w = 1322
    h = 839
    crop_img = img[y:y + h, x:x + w]
    crop_img = image_resize(crop_img, height=1440)
    cv2.imwrite('/home/pi/stoneScanner/data/pic/captrue/dbug/crop_img.png',
                crop_img)

    # img to darknnes
    # a = np.double(crop_img)
    # b = a - 60
    # dark_img = np.uint8(b)

    # get a blank canvas for drawing contour on and convert img to grayscale
    canvas = np.zeros(crop_img.shape, dtype="uint8")
    img2gray = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)

    # filter out small lines between counties
    kernel_4_2d = np.ones((5, 5), np.float32) / 25
    img2gray = cv2.filter2D(img2gray, -1, kernel_4_2d)

    # threshold the image and extract contours
    # can change cv2.threshold function thresh and max value
    ret, thresh = cv2.threshold(img2gray, 218, 255, cv2.THRESH_BINARY_INV)
    im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL,
                                                cv2.CHAIN_APPROX_NONE)
    cv2.imwrite('/home/pi/stoneScanner/data/pic/captrue/dbug/thresh.png',
                thresh)

    # another get Contours option
    # blurred = cv2.GaussianBlur(img2gray, (11, 11), 0)
    # edged = cv2.Canny(blurred, 20, 180)
    # (_, contours, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # find the stone (biggest area)
    cnt = contours[0]
    max_area = cv2.contourArea(cnt)
    for cont in contours:
        if cv2.contourArea(cont) > max_area:
            cnt = cont
            max_area = cv2.contourArea(cont)

    # define stone contour approx
    perimeter = cv2.arcLength(cnt, True)
    epsilon = 0.00001 * cv2.arcLength(cnt, True)
    approx = cv2.approxPolyDP(cnt, epsilon, True)

    cv2.drawContours(canvas, cnt, -1, (255, 255, 255), -1)
    cv2.drawContours(canvas, [approx], -1, (255, 255, 255), -1)

    # make mask
    mask_Init = np.zeros(img2gray.shape[:2], dtype=np.uint8)
    cv2.drawContours(mask_Init, [approx], -1, (255, 255, 255), -1)

    # erode mask
    kernel2Erode = np.ones((10, 10), np.uint8)
    mask_Erode = cv2.erode(mask_Init, kernel2Erode, iterations=3)

    # cut the stone
    (x, y, w, h) = cv2.boundingRect(cnt)
    stone = crop_img[y:y + h, x:x + w]
    mask_Erode = mask_Erode[y:y + h, x:x + w]

    cv2.imwrite('/home/pi/stoneScanner/data/pic/captrue/dbug/mask.png',
                mask_Erode)

    stone = cv2.bitwise_and(stone, stone, mask=mask_Erode)
    image = image_resize(stone, height=1024)

    #transparent background
    tmp = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    _, alpha = cv2.threshold(tmp, 0, 255, cv2.THRESH_BINARY)
    b, g, r = cv2.split(image)
    rgba = [b, g, r, alpha]
    result = cv2.merge(rgba, 4)
    cv2.imwrite(result_img + str(stoneNum).zfill(4) + '.png', result)

    cv2.waitKey(0)
    cv2.destroyAllWindows()
    workState.put(2)
    workState.task_done()
Exemplo n.º 58
0
import RPi.GPIO as GPIO
from picamera import PiCamera
from time import sleep
from signal import pause

#create objects that refer to a button,
#a motion sensor and the PiCamera
button = Button(2)
pir = MotionSensor(4)
camera = PiCamera()

#start the camera
camera.rotation = 180
camera.start_preview()

#image image names
i = 0

#stop the camera when the pushbutton is pressed
def stop_camera():
    camera.stop_preview()
    #exit the program
     exit()
     #take photo when motion is detected
def take_photo():
    global i
    i = i + 1
    camera.capture('/home/pi/Desktop/image_%s.jpg' % i)
    print('A photo has been taken')
    sleep(10)
Exemplo n.º 59
0
import pygame
import os,sys

import requests,json
import serial
from picamera import PiCamera
import postcardkey as pc
import ctypes
import threading
import RPi.GPIO as gpio
green=16
red=20
time.sleep(5)
camera=None
try:
    camera=PiCamera()#camera 사용중일경우 재부팅
except:
    print('camera connect error')

ser=None
#lock=threading.Lock()
user_id="0"
site_uuid='0c9808e2-f681-4085-99f9-72c46fc312ac'
session_key='0c9808e2-f681-4085-99f9-72c46fc312ac'
card_key=''

url_='http://ec2-3-36-107-134.ap-northeast-2.compute.amazonaws.com/api/truck/check_out'
url2_='http://ec2-3-36-107-134.ap-northeast-2.compute.amazonaws.com/api/truck/check_out_postprocess'
count=0
flag=0
strings=''
Exemplo n.º 60
-1
def main():
	
	print("Starting Program")
	
	# Init camera
	camera = PiCamera()
	camera.resolution = (640,480)
	camera.framerate = 24
	rawCapture = PiRGBArray(camera, size=(640,480))
	
	# allow camera to warmup
	time.sleep(0.1)
	
	# capture frames from camera
	for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
		image = frame.array
		
		cv2.imshow("Frame", image)
		key = cv2.waitKey(1) & 0xFF
		rawCapture.truncate(0)
		
		if key == ord("q"):
				break
	
	print("Completed!")
	
	return 0