Example #1
0
def anaoshots(number, fid, rid, lid, eid, camera_frame_rate):
    # initialize
    pygame.init()
    pygame.camera.init()
    # capture a image
    camera = pygame.camera.Camera("/dev/video0", (640, 480))
    camera.start()
    print("open camera success")
    c = 1
    starttime = time.time()
    while c <= number:  # 循环读取视频帧
        image = camera.get_image()
        pygame.image.save(
            image,
            r'../../data/test_data/' + os.listdir('../../data/test_data/')[0] +
            '/' + fid + '_' + rid + '_' + lid + '_' + eid + '_' + eid + '1_' +
            str(time.time()) + '.jpg')
        print('save the image', c)
        print(time.time() - starttime)
        c += 1
        usetime = time.time() - starttime

        # sleeptime = separatedtime * c - usetime
        #if sleeptime > 0: time.sleep(sleeptime)
    print('采集结束')
    camera.stop()
Example #2
0
    def __init__(self, nombre):
        FILENAME = str(nombre)
        DEVICE = '/dev/video0'
        SIZE = (640, 480)
        pygame.init()
        pygame.camera.init()
        display = pygame.display.set_mode(SIZE, 0)
        camera = pygame.camera.Camera(DEVICE, SIZE)
        camera.start()
        screen = pygame.surface.Surface(SIZE, 0, display)
        capture = True
        while capture:
            screen = camera.get_image(screen)
            display.blit(screen, (0, 0))
            pygame.display.flip()
            for event in pygame.event.get():
                if event.type == KEYDOWN and event.key == K_s:
                    os.chdir("imagenes")
                    print("guardado")
                    pygame.image.save(screen, FILENAME)
                    os.chdir("..")
                    capture = False

        camera.stop()
        pygame.quit()
        return
Example #3
0
def camstream():
    DEVICE = '/dev/video0'
    SIZE = (640, 480)
    FILENAME = 'capture.png'
    pygame.init()
    pygame.camera.init()
    display = pygame.display.set_mode(SIZE, 0)
    camera = pygame.camera.Camera(DEVICE, SIZE)
    camera.start()
    screen = pygame.surface.Surface(SIZE, 0, display)
    capture = True
    while capture:
        screen = camera.get_image(screen)
        pil_string_image = pygame.image.tostring(screen,"RGBA",False)
        im=Image.frombytes("RGBA",(640,480),pil_string_image)
        im.show()
        time.sleep(0.5)
        im.close()
        display.blit(screen, (0,0))
        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == QUIT:
                capture = False
            elif event.type == KEYDOWN and event.key == K_s:
                pygame.image.save(screen, FILENAME)
    camera.stop()
    pygame.quit()
    return
Example #4
0
def captureImage():

    global captureSoundSeq

    if (captureSoundSeq == 1):
        sdInit.play()
    if (captureSoundSeq == 2):
        sdConf.play()
    if (captureSoundSeq == 3):
        sdBegin.play()

    captureSoundSeq = captureSoundSeq + 1
    if (captureSoundSeq > 3):
        captureSoundSeq = 1

    camera = pygame.camera.Camera(DEVICE, (800, 480), "RGB")
    camera.start()
    sleep(.25)
    camGrab = camera.get_image()

    #create a new animation canvas
    animFrame = pygame.Surface(lastScreen.get_size())
    animFrame = animFrame.convert()
    pygame.draw.rect(animFrame, (0, 0, 0), (0, 0, 800, 480))
    lastScreen.blit(animFrame, (0, 0))

    capture = True
    camGrab = pygame.transform.flip(camGrab, False, True)

    while capture:
        if camera.query_image():
            captureSurface = camera.get_image()
        # flipping image
        captureSurface = pygame.transform.flip(captureSurface, False, True)
        display.blit(captureSurface, (0, 0))
        pygame.display.flip()

        if shutterButton.is_pressed:
            pygame.image.save(display, ("CapturedImages/" + photoFileName))
            shutterSound.play()

            flashFrame = pygame.Surface(lastScreen.get_size())
            flashFrame = flashFrame.convert()
            pygame.draw.rect(display, (255, 255, 255), (0, 0, 800, 480))
            pygame.display.flip()
            sleep(.25)
            capture = False

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                appRunning = False
                break
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    pygame.quit()
                    appRunning = False
                    break
    camera.stop()
    return
Example #5
0
def scan_code(device, size):
    pygame.init()
    pygame.camera.init()
    display = pygame.display.set_mode(size, 0)
    pygame.display.set_caption("Scan QR-code here")
    camera = pygame.camera.Camera(device, size)
    camera.start()
    screen = pygame.surface.Surface(size, 0, display)
    capture = True
    while capture:
        screen = camera.get_image(screen)
        display.blit(screen, (0, 0))
        pygame.display.flip()
        string = pygame.image.tostring(screen, "RGBA", False)
        image = Image.frombytes("RGBA", size, string)
        codes = zbarlight.scan_codes('qrcode', image)
        if codes:
            code = codes[0]
            capture = False
        for event in pygame.event.get():
            if event.type == QUIT:
                capture = False
    camera.stop()
    pygame.quit()
    code = str(code)
    code = code[2:len(code) - 1]
    return code
Example #6
0
def camstream():
    '''
    The bulk of the camera code was not written by us, since it's just here for fun
    and does not contribute to the actual game in any meaningful way.
    We use this to make a avatar for the user on the fly
    modified from https://gist.github.com/snim2/255151
    works only in linux, or by installing some dependency in windows [not tested]
    '''
    try:
        DEVICE = '/dev/video0'
        SIZE = (640, 480)
        FILENAME = 'assets/avatar.png'
        import pygame.camera
        pygame.camera.init()
        display = pygame.display.set_mode((800, 60 * 8), 0)
        camera = pygame.camera.Camera(DEVICE, SIZE)
        camera.start()
        screen = pygame.surface.Surface(SIZE, 0, display)
        screen = camera.get_image(screen)
        pygame.image.save(screen, FILENAME)
        camera.stop()
        return
    except:
        # if camera fails to take a picture, use backup generic avatar
        from shutil import copyfile
        copyfile('assets/backupavatar.png', 'assets/avatar.png')
Example #7
0
File: av.py Project: ucontent/guild
    def gen_process(self):
        device = "/dev/video0"

        capturesize = vidsize
        camera = pygame.camera.Camera(device, capturesize)
        camera.start()
        count = 0
        ts = time.time()
        print("START")
        while True:
            time.sleep(0.02)
            yield 1
            count += 1
            snapshot = camera.get_image()
            now = time.time()
            try:
                self.produce(snapshot, now)
            except:
                pass
            if count > 30:
                print(ts, time.time(), "Count", count, end="")
                dur = time.time() - ts
                if dur > 0:
                    print("RATE: ", count / (time.time() - ts))
                count = 0
                ts = time.time()
Example #8
0
File: av.py Project: bbcrd/guild
    def gen_process(self):
        device = "/dev/video0"

        capturesize = vidsize
        camera = pygame.camera.Camera(device, capturesize)
        camera.start()
        count = 0
        ts = time.time()
        print("START")
        while True:
            time.sleep(0.02)
            yield 1
            count += 1
            snapshot = camera.get_image()
            now = time.time()
            try:
                self.produce(snapshot, now)
            except:
                pass
            if count > 30:
                print(ts, time.time(), "Count", count, end="")
                dur = time.time() - ts
                if dur > 0:
                    print("RATE: ", count / (time.time() - ts))
                count = 0
                ts = time.time()
def camstream():
    pygame.init()
    pygame.camera.init()
    display = pygame.display.set_mode(SIZE, 0)
    camera = pygame.camera.Camera(DEVICE, SIZE)
    camera.start()
    screen = pygame.surface.Surface(SIZE, 0, display)
    capture = True
    while capture:
        screen = camera.get_image(screen)
        display.blit(screen, (0,0))
        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == QUIT:
                capture = False
            elif event.type == KEYDOWN:
                im = pygame.image.save(screen, FILENAME)
                camera.stop()
                pygame.quit()
                capture = False
                Button_Example()

    camera.stop()
    pygame.quit()
    return
Example #10
0
def camstream():
    count = 0
    pygame.init()
    pygame.camera.init()
    display = pygame.display.set_mode(SIZE, 0)
    camera = pygame.camera.Camera(DEVICE, SIZE)
    camera.start()
    screen = pygame.surface.Surface(SIZE, 0, display)

    capture = True
    while capture:
        screen = camera.get_image(screen)
        display.blit(screen, (0,0))
        pygame.display.flip()
        pygame.time.wait(100)
        pygame.image.save(screen, "frame%d.jpg" % count)
        count += 1
        if count > 20:
            break


        # for event in pygame.event.get():
        #     if event.type == QUIT:
        #         capture = False
        #     elif event.type == KEYDOWN and event.key == K_x:
        #         pygame.image.save(screen, "frame%d.jpg" % count)
        #         count += 1
    camera.stop()
    pygame.quit()
    return
Example #11
0
def camstream():
    pygame.init()
    pygame.camera.init()
    display = pygame.display.set_mode(SIZE, 0)
    camera = pygame.camera.Camera(DEVICE, SIZE)
    camera.start()
    screen = pygame.surface.Surface(SIZE, 0, display)
    capture = True
    while capture:
        screen = camera.get_image(screen)
        display.blit(screen, (0, 0))
        pygame.display.flip()
        string = pygame.image.tostring(screen, "RGBA", False)
        image = Image.frombytes("RGBA", SIZE, string)
        codes = zbarlight.scan_codes('qrcode', image)
        if codes:
            print('QR codes: %s' % codes[0])
        for event in pygame.event.get():
            if event.type == QUIT:
                capture = False
            elif event.type == KEYDOWN and event.key == K_s:
                pygame.image.save(screen, FILENAME)
                print("saved")
    camera.stop()
    pygame.quit()
    return
def camstream():
    bluetoothSerial = serial.Serial("/dev/rfcomm0", baudrate=9600)
    pygame.init()
    pygame.camera.init()

    DEVICE = pygame.camera.list_cameras()
    SIZE = (640, 480)
    FILENAME = 'capture.png'

    display = pygame.display.set_mode(SIZE, 0)
    camera = pygame.camera.Camera(DEVICE[0], SIZE)
    camera.start()
    screen = pygame.surface.Surface(SIZE, 0, display)
    capture = True
    while capture:
        screen = camera.get_image(screen)
        display.blit(screen, (0, 0))
        pygame.display.flip()
        isStealed = bluetoothSerial.readline().decode("utf-8")
        #for event in pygame.event.get():
        #    if event.type == QUIT:
        #        capture = False
        #    elif event.type == KEYDOWN and event.key == K_s:
        #        pygame.image.save(screen, FILENAME)
        if isStealed == "1111" or "2222" or "3333" or "4444" or "5555" or "6666" or "7777":
            pygame.image.save(screen, FILENAME)
    camera.stop()
    pygame.quit()
    return
Example #13
0
def capture_images():

    DEVICE = '/dev/video0'
    SIZE = (640, 480)
    FILENAME = '/media/abisek/Important Files/R.K/++/Machine Learning/Projects/K/captures/capturetest'

    pygame.init()
    pygame.camera.init()
    display = pygame.display.set_mode(SIZE, 0)
    camera = pygame.camera.Camera(DEVICE, SIZE)
    camera.start()
    screen = pygame.surface.Surface(SIZE, 0, display)
    capture = True
    count = 0
    while capture:
        screen = camera.get_image(screen)
        display.blit(screen, (0, 0))
        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == KEYDOWN and event.key == 113:
                capture = False
            elif event.type == KEYDOWN and event.key == 97:
                pygame.image.save(screen, FILENAME + str(count) + '.jpg')
                count += 1
    camera.stop()
    pygame.quit()
def camstream():
    pygame.init()
    pygame.camera.init()
    display = pygame.display.set_mode(SIZE, 0)
    #try to go fullscreen
    #display = pygame.display.set_mode((1920,1080),pygame.FULLSCREEN)
    #does bot work due to resolution limit?

    #hide mouse
    pygame.mouse.set_visible(0)

    camera = pygame.camera.Camera(DEVICE, SIZE, "HSV")
    camera.start()
    screen = pygame.surface.Surface(SIZE, 0, display)
    capture = True
    while capture:
        screen = camera.get_image(screen)
        display.blit(screen, (0, 0))
        pygame.display.flip()
        #this is for capturing an image
        for event in pygame.event.get():
            if event.type == QUIT:
                capture = False
            elif event.type == KEYDOWN and event.key == K_s:
                pygame.image.save(screen, FILENAME)
    camera.stop()
    pygame.quit()
    return
Example #15
0
def camstream():
    pygame.init()
    pygame.camera.init()
    display = pygame.display.set_mode((1280, 960), 0)
    camera = pygame.camera.Camera(DEVICE, SIZE)
    camera.start()
    screen = pygame.surface.Surface(SIZE, 0, display)
    capture = True
    time.sleep(1)
    initial = camera.get_image(screen).copy()
    height = initial.get_height()
    width = initial.get_width()
    print(height)
    print(width)
    print(initial.get_at([0,0]))
    print(averagepix(initial))
    while capture:
        initial = camera.get_image(screen).copy()
        screen = camera.get_image(screen)
        screen = surfdiff(screen,initial)
        derr = pygame.transform.scale2x(pygame.transform.flip(screen.copy(),True,False))
        display.blit(derr,(5,5))
        pygame.display.flip()
        #pygame.display.update()
        for event in pygame.event.get():
            if event.type == QUIT:
                capture = False
            elif event.type == KEYDOWN and event.key == K_s:
                pygame.image.save(screen, FILENAME)
    camera.stop()
    pygame.quit()
    return
Example #16
0
 def on_startup(self):
     """Start the camera and return the camera instance"""
     pygame.camera.init()
     self.camera = camera = pygame.camera.Camera(
         pygame.camera.list_cameras()[0])
     camera.start()
     self.log.debug('camera started')
Example #17
0
 def jalankanKamera(self):
     DEVICE = '/dev/video0'
     SIZE = (640,480)
     FILENAME = 'capture'+str(self.penghitung)+'.png'
     pygame.init()
     pygame.camera.init()
     display = pygame.display.set_mode(SIZE, 0)
     camera = pygame.camera.Camera(DEVICE, SIZE)
     camera.start()
     screen = pygame.surface.Surface(SIZE, 0, display)
     pygame.display.set_caption("Kamera Gabut qywok")
     capture = True
     while capture:
         screen = camera.get_image(screen)
         display.blit(screen, (0,0))
         pygame.display.flip()
         for event in pygame.event.get():
             if event.type == pygame.QUIT:
                 capture = False
             elif event.type == pygame.KEYDOWN and event.key == K_SPACE:
                 pygame.image.save(screen, FILENAME)
                 camera.stop()
                 pygame.quit()
                 self.isi.set('Mulai Lagi')
                 self.ucapan.set("Selamat...!! gambar anda telah tersimpan...\n"
                                     "dengan nama 'capture"+str(self.penghitung)+".png' silahkan di cek di \n"
                                     "folder tempat anda menyimpan file python nya..\n"
                                     "Untuk memulai untuk memotret lagi, silahkan tekan\n"
                                     "tombol 'mulai lagi' dan ingat tekan tombol 'spasi'\n"
                                     "untuk mengambil gambar.")
                 self.penghitung+=1
                 return
     camera.stop()
     pygame.quit()
     return
Example #18
0
def camstream():
    global capture
    global distance
    global distdelay
    global elwidth
    global elheight
    global formoverlay
    global area
    global distance_glob
    global pictureVar
    pygame.init()
    pygame.camera.init()
    display = pygame.display.set_mode(SIZE, 0)
    camera = pygame.camera.Camera(DEVICE, SIZE)
    camera.start()
    screen = pygame.surface.Surface(SIZE, 0, display)
    pygame.mouse.set_visible(0)
    thread = Thread(target=rotaryThread)
    thread.start()
    while capture:
        if (not pictureVar):
            frame = camera.get_image(screen)
            frame = modFrame(frame)
            if (formoverlay == 1):
                pygame.draw.ellipse(frame, BLACK, [
                    80 - (elwidth / 2), 64 - (elheight / 2), elwidth, elheight
                ], 3)
            if (formoverlay == 2):
                pygame.draw.rect(frame, BLACK, [
                    80 - (elwidth / 2), 64 - (elheight / 2), elwidth, elheight
                ], 3)
            frame = pygame.transform.rotozoom(frame, 270, 0.8)
            display.fill((0, 0, 0))
            display.blit(frame, (0, 0))
            if (distdelay > 10):
                #distance = round(distanz(), 0)
                thread2 = Thread(target=distanz)
                thread2.start()
                distdelay = 0
                if (formoverlay == 2):
                    area = calc_area_rect(distance_glob, elwidth, elheight)
                elif (formoverlay == 1):
                    area = calc_area_ellipse(distance_glob, elwidth, elheight)
            distdelay = distdelay + 1

            displaytext("Dist: " + str(distance_glob), 18, 3, (250, 100, 100),
                        False, display)
            displaytext("Area: " + str(area), 25, 1, (250, 100, 100), False,
                        display)
            pygame.display.flip()
            for event in pygame.event.get():
                handle(event)
        else:
            displaytext("Saved", 18, 2, (0, 0, 0), False, display)
            pygame.display.flip()

    camera.stop()
    pygame.quit()
    GPIO.cleanup()
    return
Example #19
0
    def capture_image_pygame(self, camera_path: str, image_path: str) -> None:
        """Captures an image with pygame."""
        self.logger.debug("Capturing image from camera: {}".format(camera_path))

        # Capture image
        try:

            # Check if simulated
            # if self.simulate:
            #     message = "Simulating capture, saving image to: {}".format(image_path)
            #     self.logger.info(message)
            #     command = "cp {} {}".format(self.SIMULATION_IMAGE_PATH, image_path)
            #     os.system(command)
            #     return

            # Capture and save image
            if not self._simulate_capture(image_path):
                resolution_array = self.resolution.split("x")
                resolution = (int(resolution_array[0]), int(resolution_array[1]))
                camera = pygame.camera.Camera(camera_path, resolution)
                camera.start()
                image = camera.get_image()
                pygame.image.save(image, image_path)
                camera.stop()

        except Exception as e:
            raise exceptions.CaptureImageError(logger=self.logger) from e
Example #20
0
    def do_scan(self):
        display = pygame.display.set_mode(self.videosize, 0)
        pygame.display.iconify()
        camera = pygame.camera.Camera(self.camera, self.videosize)
        camera.start()
        screen = pygame.surface.Surface(self.videosize, 0, display)
        Locked = True

        while Locked:
            img = camera.get_image(screen)
            pygame.image.save(img, repertoire_script + 'data{}image.jpg'.format(os.sep))
            img = Image.open(repertoire_script + 'data{}image.jpg'.format(os.sep))
            codes = pyzbar.decode(img)
            if len(codes) > 0:
                Locked = False
            text = pytesseract.image_to_string(Image.open(repertoire_script + 'data{}image.jpg'.format(os.sep)))
            if len(text) > 0:
                Locked = False
            time.sleep(2)
        os.remove(repertoire_script + 'data{}image.jpg'.format(os.sep))
        camera.stop()

        for l in codes:
            donnees = l.data.decode('utf-8')
            print(_('Données du code: {}'.format(donnees)))
        donnees = '{}\n{}'.format(donnees, text)
        try:
            pyperclip.copy(donnees)
        except:
            if self.debug:
                print(_('Impossible de copier le texte.'))

        self.destroy()
def capture_image(): 
    camera.start()
    pygame_surface = camera.get_image()
    camera.stop()

    pil_string_image = pygame.image.tostring(pygame_surface, 'RGB', False)
    image = Image.frombytes('RGB', (CANVAS_WIDTH, CANVAS_HEIGHT), pil_string_image)
    return image
Example #22
0
 def gen_process(self):
     camera = pygame.camera.Camera(pygame.camera.list_cameras()[0])
     camera.start()
     while True:
         yield 1
         frame = camera.get_image()
         self.output(frame)
         time.sleep(1.0 / 50)
Example #23
0
 def gen_process(self):
     camera = pygame.camera.Camera(pygame.camera.list_cameras()[0])
     camera.start()
     while True:
         yield 1
         frame = camera.get_image()
         self.output(frame)
         time.sleep(1.0 / 50)
Example #24
0
def camstream():
    pygame.init()
    clock = pygame.time.Clock()
    pygame.camera.init()

    pprint.pprint(pygame.camera.list_cameras())

    display = pygame.display.set_mode(screen_size, pygame.FULLSCREEN)
    camera = pygame.camera.Camera(DEVICE, camera_size)
    camera.start()

    actual_camera_size = camera.get_size()
    pprint.pprint(actual_camera_size)

    screen = pygame.surface.Surface(screen_size, 0, display)
    frame = pygame.surface.Surface(camera_size, 0, display)
    detect = pygame.surface.Surface(detect_size, 0, display)
    capture = True
    while capture:

        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if event.key == K_s:
                    capture = False
                elif event.type == KEYDOWN:
                    if event.key == K_s:
                        pygame.image.save(screen, FILENAME)
                    elif event.key == K_q:
                        capture = False
        if camera.query_image():
            camera.get_image(frame)

            pygame.transform.scale(frame, screen_size, screen)
            pygame.transform.flip(screen, True, False)
            # make a rect in the middle of the screen
            capture_rect = pygame.draw.rect(screen, (255, 255, 255),
                                            (390, 230, 20, 20), 1)
            # get the average color of the area inside the rect
            capture_colour = pygame.transform.average_color(
                screen, capture_rect)

            pygame.transform.scale(screen, detect_size, detect)
            pygame.transform.laplacian(detect, detect)
            # pygame.transform.threshold(detect, capture_colour, (90, 170, 170), (0, 0, 0), 2)

            display.blit(screen, (0, 0))

            # fill the upper left corner with that color
            display.fill(capture_colour, (0, 0, 24, 24))

            display.blit(detect, detect_origin)

        pygame.display.flip()
        dt = clock.tick(10)

    camera.stop()
    pygame.quit()
    return
Example #25
0
def getTestPictures(directory):
	camera = initializeCamera(CAM_INDEX)
	camera.start()

	user_directory = directory
	if not os.path.exists(user_directory):
		os.mkdir(user_directory)

	takePictures(camera, user_directory)
Example #26
0
def ampilight():
    try:
        pixelArray = dotstar.DotStar(board.SCK,
                                     board.MOSI,
                                     X + 2 * Y,
                                     brightness=0.3,
                                     auto_write=False,
                                     baudrate=20000000)
        pixelArray.fill((0, 0, 0))

        pygame.init()
        pygame.camera.init()
        camera = pygame.camera.Camera(DEVICE, SIZE_CAPTURE)
        screen = pygame.surface.Surface(SIZE_CAPTURE)
        tiny = pygame.surface.Surface((10, 5))
        pixelMatrix = pygame.surface.Surface(SIZE_LED)

        camera.start()
        while True:
            camera.get_image(screen)
            pygame.transform.smoothscale(screen, (10, 5), tiny)
            pygame.transform.smoothscale(tiny, SIZE_LED, pixelMatrix)

            # right panel
            if True:
                idx = 0
                for y in range(Y - 1):
                    pixelArray[idx] = pixelMatrix.get_at(
                        (X - 1 - OFFSET, Y - 1 - y))[:3]
                    idx += 1

            # top panel
            if True:
                idx = 23
                for x in range(X):
                    pixelArray[idx] = pixelMatrix.get_at(
                        (X - 1 - x, OFFSET))[:3]
                    idx += 1

            # left panel
            if True:
                idx = 64
                for y in range(Y - 1):
                    pixelArray[idx] = pixelMatrix.get_at(
                        (0 + OFFSET, y + 1))[:3]
                    idx += 1

            pixelArray = blackLevelCorrection(pixelArray)
            pixelArray.show()

    finally:
        print('stopping ...')
        pixelArray.fill((0, 0, 0))
        camera.stop()
        pygame.quit()
    return
Example #27
0
def camstream():
    pygame.init()
    pygame.display.set_caption("อ่าน BARCODE & QRCODE จาก กล้องเว็บแคม USB")
    display = pygame.display.set_mode(SIZE0, 0, 24)

    f01 = pygame.font.Font("Garuda-Bold.ttf", 12)

    pygame.camera.init()
    camera = pygame.camera.Camera(DEVICE0, SIZECAM)
    camera.start()
    surfcam = pygame.surface.Surface(SIZECAM, depth=24)

    FPS = 25
    clock = pygame.time.Clock()
    running = True
    while running:
        camera.get_image(surfcam)
        display.blit(surfcam, (0, 0))

        xrect1 = pygame.Rect(0, CAMH, CAMW, 20)
        pygame.draw.rect(display, xcolor[0], xrect1)
        msgcam = "คลิกซ้าย..อ่าน BARCODE   คลิกขวา..อ่าน QRCODE"
        display.blit(f01.render(msgcam, True, xcolor[1]), (10, CAMH))

        pygame.display.flip()

        for event in pygame.event.get():
            #event quit
            if event.type == QUIT:
                running = False
            elif event.type == KEYDOWN and event.key == K_q:
                running = False

            elif event.type == pygame.MOUSEBUTTONDOWN:
                #[1=Lclick 3=Rclick  2=Mclick  4=ScrUp 5=ScrDN]
                if (event.button == 1):  #event zbar
                    ximgndarray = getimg_ndarray(surfcam)
                    xrtns = convzbar(ximgndarray)
                if (event.button == 3):  #event zbarlight
                    xfile = 'filecam.png'
                    pygame.image.save(surfcam, xfile)
                    xrtns = convzbarlight(xfile)

                display.blit(surfcam, (CAMW, 0))
                xrect2 = pygame.Rect(CAMW, CAMH, CAMW, 20)
                pygame.draw.rect(display, xcolor[2], xrect2)
                msgzbar = xrtns[0]
                display.blit(f01.render(msgzbar, True, xcolor[0]),
                             (CAMW + 10, CAMH))

        pygame.display.flip()
        clock.tick(FPS)

    camera.stop()
    pygame.quit()
    return
Example #28
0
def camstream():
    #--init
    pygame.init()
    display = pygame.display.set_mode(SIZE, 0)
    pygame.display.set_caption("ทดสอบ USB Webcam")

    pygame.camera.init()
    camera = pygame.camera.Camera(DEVICE, SIZE)
    camera.start()
    screen = pygame.surface.Surface(SIZE, 0, display)

    #--loop
    FPS = 25  #--frame per sec
    clock = pygame.time.Clock()
    running = True

    while running:
        #camera background
        screen = camera.get_image(screen)

        #rectangle
        xcolor = (255, 255, 0)
        xrect = pygame.Rect(0, Cheight - 20, Cwidth, 20)
        pygame.draw.rect(screen, xcolor, xrect)

        display.blit(screen, (0, 0))
        #text
        xcolor = (0, 0, 255)
        f00 = pygame.font.Font(None, 14)
        f01 = pygame.font.Font("Garuda-Bold.ttf", 12)
        msg = "C101: ประตูหน้า   " + time.strftime(" %d-%m-%Y  %I:%M:%S %p")
        display.blit(f01.render(msg, True, xcolor), (10, Cheight - 20))

        #flip
        pygame.display.flip()

        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            elif event.type == KEYDOWN and event.key == K_s:
                #save imagefile
                xfilename = FILEPATH + time.strftime("pic%Y-%m-%d--%H%M%S.jpg")
                pygame.image.save(display, xfilename)
                print(">>save image file: %s \n" % xfilename)

                #line_notify+image upload
                xrtn = LNF.line_notifyIMG("test usbcam", xfilename, headers)
                print("LINE>> status code, error string , total time\n ", xrtn)

        clock.tick(FPS)

    #--exit
    camera.stop()
    pygame.quit()
    return
Example #29
0
def main():
    parser = ArgParser(SIZE[0], SIZE[1])
    X1, Y1, X2, Y2 = 0, 0, SIZE[0], SIZE[1]
    try:
        X1, Y1, X2, Y2 = parser.parse()
    except IncorrectArgumentsException as e:
        print("ERROR: ", e)
        end()

    camera = tryInitCamera()
    pygame.event.set_allowed([KEYDOWN])

    display = pygame.display.set_mode(SIZE, 0)

    camera.start()
    screen = pygame.surface.Surface(SIZE, 0, display)
    capture = True

    prev2 = None
    prev2Part = None
    prev = camera.get_image().convert()
    prevPart = toGrayscale(prev, tl=(X1, Y1), br=(X2, Y2))
    curr = camera.get_image().convert()
    currPart = toGrayscale(curr, tl=(X1, Y1), br=(X2, Y2))

    file = open("../results/pg_times.csv", "a")
    size = (X2 - X1) * (Y2 - Y1)

    i = 0
    while i < frames:
        i += 1
        prev2 = prev
        prev2Part = prevPart
        prev = curr
        prevPart = currPart
        curr = camera.get_image().convert()

        start_time = time.clock_gettime(CPUTIME)
        currPart = toGrayscale(curr, tl=(X1, Y1), br=(X2, Y2))
        diff = diffImg(prev2Part, prevPart, currPart, tl=(X1, Y1), br=(X2, Y2))
        end_time = time.clock_gettime(CPUTIME)

        elapsed = end_time - start_time
        file.write(str(size) + ", " + str(round(elapsed * 1000000000)) + "\n")

        frame = copy(curr)
        frame.blit(diff, (X1, Y1))
        display.blit(frame, (0, 0))
        pygame.display.flip()
        for event in pygame.event.get():
            if event.type == KEYDOWN and event.key == K_q:
                capture = False
                break
    file.close()
    end(camera)
Example #30
0
def cameraStream():
	#Initialize camera
	pygame.init()
	pygame.camera.init()

	#set window size
	display = pygame.display.set_mode((320,400),0)

	#get camera list and selet first camera
	cameraList = pygame.camera.list_cameras()
	if cameraList:
		camera = pygame.camera.Camera(cameraList[0],SIZE)

	#start the camera
	camera.start()

	sensor = DistanceSensor(echo=17, max_distance=3, trigger=4)

	#crate a surface to capture to
	screen = pygame.surface.Surface(SIZE, 0, display)
	
	working = True

	while working:
		display.fill(BLACK)
		#display image
		screen = camera.get_image(screen)
		#blit to the display surface
		display.blit(screen, (0,0))

		dist = readSensor(sensor)
		if  dist > 30:
			time = "MOVE"
		else:
			time = "STOP"

		font_big = pygame.font.Font(None, 50)           # font size
		text_surface = font_big.render('%d cm = %s'%(dist,time),True, (255,150,0))	
		
		rect = text_surface.get_rect(center=(160,350))  # position
		
		display.blit(text_surface, rect)

		pygame.display.flip()
		pygame.display.update()
		events = pygame.event.get()
		for e in events:
			if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
				#exit
				working = False
	camera.stop()
	pygame.quit()
	return
Example #31
0
def eval_anaoshots():
    # initialize
    pygame.init()
    pygame.camera.init()
    # capture a image
    camera = pygame.camera.Camera("/dev/video0", (640, 480))
    camera.start()
    print("open camera success")

    while (True):

        time.sleep(0.1)
        with open('../param', 'r') as f:
            for i, line in enumerate(f):
                if i == 0: flag = line.strip()  #开始暂停标志位
                if i == 1: camera_frame_rate = line.strip()  #帧率
                if i == 2: camera_exposure_time = line.strip()  #曝光时间
                if i == 3: fid = line.strip()
                if i == 4: rid = line.strip()
                if i == 5: lid = line.strip()
                if i == 6: eid = line.strip()
            print('param1 = ', flag.rstrip())
            print('camera_frame_rate = ', camera_frame_rate)
            separatedtime = 1 / float(camera_frame_rate)  # 每隔0.1s读取一帧
            if flag == '1':
                pass
            elif flag == '0':

                time.sleep(separatedtime)
                c = 0
                number = 2
                starttime = time.time()

                while True:  # 循环读取视频帧
                    image = camera.get_image()
                    pygame.image.save(
                        image, r'../../data/test_data/' +
                        os.listdir('../../data/test_data/')[0] + '/' + fid +
                        '_' + rid + '_' + lid + '_' + eid + '_' + eid + '1_' +
                        str(time.time()) + '.jpg')
                    print('save the image')

                    print(time.time() - starttime)
                    c += 1
                    if c >= number:
                        break
                    usetime = time.time() - starttime
                    sleeptime = separatedtime * c - usetime
                    if sleeptime > 0: time.sleep(sleeptime)
            else:
                continue
    print('close')
    camera.stop()
Example #32
0
def main():
    default_model_dir = '../all_models'
    default_model = 'mobilenet_v2_1.0_224_quant_edgetpu.tflite'
    default_labels = 'imagenet_labels.txt'
    parser = argparse.ArgumentParser()
    parser.add_argument('--model',
                        help='.tflite model path',
                        default=os.path.join(default_model_dir, default_model))
    parser.add_argument('--labels',
                        help='label file path',
                        default=os.path.join(default_model_dir,
                                             default_labels))
    args = parser.parse_args()

    with open(args.labels, 'r') as f:
        pairs = (l.strip().split(maxsplit=1) for l in f.readlines())
        labels = dict((int(k), v) for k, v in pairs)

    interpreter = common.make_interpreter(args.model)
    interpreter.allocate_tensors()

    pygame.init()
    pygame.camera.init()
    camlist = pygame.camera.list_cameras()

    print('By default using camera: ', camlist[-1])
    camera = pygame.camera.Camera(camlist[-1], (640, 480))
    width, height, channels = common.input_image_size(interpreter)
    camera.start()
    try:
        fps = deque(maxlen=20)
        fps.append(time.time())
        while True:
            imagen = camera.get_image()
            imagen = pygame.transform.scale(imagen, (width, height))
            input = np.frombuffer(imagen.get_buffer(), dtype=np.uint8)
            start_ms = time.time()
            common.input_tensor(interpreter)[:, :] = np.reshape(
                input, (common.input_image_size(interpreter)))
            interpreter.invoke()
            results = get_output(interpreter, top_k=3, score_threshold=0)
            inference_ms = (time.time() - start_ms) * 1000.0
            fps.append(time.time())
            fps_ms = len(fps) / (fps[-1] - fps[0])
            annotate_text = 'Inference: {:5.2f}ms FPS: {:3.1f}'.format(
                inference_ms, fps_ms)
            for result in results:
                annotate_text += '\n{:.0f}% {}'.format(100 * result[1],
                                                       labels[result[0]])
            print(annotate_text)
    finally:
        camera.stop()
def main():
    default_model_dir = '../all_models'
    default_model = 'mobilenet_v2_1.0_224_quant_edgetpu.tflite'
    default_labels = 'imagenet_labels.txt'
    parser = argparse.ArgumentParser()
    parser.add_argument('--model',
                        help='.tflite model path',
                        default=os.path.join(default_model_dir, default_model))
    parser.add_argument('--labels',
                        help='label file path',
                        default=os.path.join(default_model_dir,
                                             default_labels))
    args = parser.parse_args()

    with open(args.labels, 'r') as f:
        pairs = (l.strip().split(maxsplit=1) for l in f.readlines())
        labels = dict((int(k), v) for k, v in pairs)

    interpreter = make_interpreter(args.model)
    interpreter.allocate_tensors()

    pygame.init()
    pygame.camera.init()
    camlist = pygame.camera.list_cameras()

    print('By default using camera: ', camlist[-1])
    camera = pygame.camera.Camera(camlist[-1], (640, 480))
    inference_size = input_size(interpreter)
    camera.start()
    try:
        last_time = time.monotonic()
        while True:
            imagen = camera.get_image()
            imagen = pygame.transform.scale(imagen, inference_size)
            start_ms = time.time()
            run_inference(interpreter, imagen.get_buffer().raw)
            results = get_classes(interpreter, top_k=3, score_threshold=0)
            stop_time = time.monotonic()
            inference_ms = (time.time() - start_ms) * 1000.0
            fps_ms = 1.0 / (stop_time - last_time)
            last_time = stop_time
            annotate_text = 'Inference: {:5.2f}ms FPS: {:3.1f}'.format(
                inference_ms, fps_ms)
            for result in results:
                annotate_text += '\n{:.0f}% {}'.format(100 * result[1],
                                                       labels[result[0]])
            print(annotate_text)
    finally:
        camera.stop()
Example #34
0
def main():

    # Init framebuffer/touchscreen environment variables
    os.putenv('SDL_VIDEODRIVER', 'fbcon')
    os.putenv('SDL_FBDEV', '/dev/fb1')
    os.putenv('SDL_MOUSEDRV', 'TSLIB')
    os.putenv('SDL_MOUSEDEV', '/dev/input/touchscreen')
    (x, y) = (0, 0)

    pygame.init()
    pygame.camera.init()
    pygame.font.init()
    pygame.mouse.set_visible(False)

    font = pygame.font.SysFont('Comic Sans MS', 24)
    screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
    camera = pygame.camera.Camera("/dev/video0", (640, 480))
    camera.start()

    while True:
        snapshot = camera.get_image()
        screen.blit(snapshot, (x, y))

        for event in pygame.event.get():
            # take picture
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                filename = "/tmp/camera.jpg"
                pygame.image.save(snapshot, filename)
                cmd = '/home/pi/src/DeepBeliefSDK/source/jpcnn -i ' + filename + ' -n /home/pi/src/DeepBeliefSDK/networks/jetpac.ntwk  -m s'
                proc = subprocess.Popen(cmd,
                                        shell=True,
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.STDOUT)
                stdout, stderr = proc.communicate()
                result = ["0.0", ""]
                for line in stdout.splitlines():
                    data = line.split("\t")
                    if float(result[0]) < float(data[0]):
                        result = data
                textsurface = font.render(result[1], False, (0, 0, 0))
                screen.blit(textsurface, (0, 0))
                pygame.display.update()
                pygame.time.wait(2000)
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()
        pygame.time.wait(30)
Example #35
0
def main():
    global IP, TEMPLATE
    # Parse command-line options
    parser = OptionParser()
    parser.add_option('-i', '--ip', dest='ip', help='Server IP address')
    options, _ = parser.parse_args()
    if options.ip == None:
        print 'Error: You must give the IP address.\nRun with -h to see usage.'
        sys.exit(0)
    IP = options.ip

    # Read template file
    with open('webcam.html') as htmlfile:
        TEMPLATE = htmlfile.read()

    
    # Initialize Pygame and camera
    pygame.init()
    pygame.camera.init()

    cam_list = pygame.camera.list_cameras()
    print 'Camlist', cam_list
    if len(cam_list) == 0:
        print 'No camera found.'
        pygame.quit()
        sys.exit(-1)

    if platform.uname()[0] != 'Windows':
        camera = pygame.camera.Camera(cam_list[0], (320, 240))
        camera.start()

        camthread = CameraThread(camera)
        camthread.start()
    else:
        camthread = None

    # Start server
    server = HTTPServer((IP, PORT), HTTPHandler)
    print "Webcam server running at", (IP, PORT)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print '\nClosing server.'
        server.socket.close()

    if camthread:
        camthread.stop_capture()
    pygame.quit()
def show_camera_until(button):
    global screen
    font = pygame.font.Font(None, 36)
    text = font.render(u"Zum Loslegen: Roten Knopf drücken.", True, (128, 128, 128))
    #screen = init_pygame()
    pixel_width = 1024
    pixel_height = 768
    camera = pygame.camera.Camera("/dev/video0",(pixel_width,pixel_height))
    camera.start()
    while GPIO.input(button) == GPIO.HIGH:
      image = camera.get_image()
      screen.blit(image,(offset_x,offset_y))
      screen.blit(text,(512 - text.get_width() // 2, 384 - text.get_height() // 2))
      pygame.display.flip()
      sleep(0.0001)
    camera.stop()
def main():
	#init game, camera, display
	pygame.init()
	leckerli_font = pygame.font.Font("fonts/LeckerliOne-Regular.ttf", 35)
	anon_font	  = pygame.font.Font('fonts/slkscr.ttf', 15)
	anon_font_bold= pygame.font.Font('fonts/slkscrb.ttf', 15)
	pygame.camera.init()
	infoObject = pygame.display.Info()
	#SIZE = (infoObject.current_w, infoObject.current_h)
	screen = pygame.display.set_mode(SIZE, 0)#FULLsurface)
	camera = pygame.camera.Camera(DEVICE, CAMERA_SIZE)
	camera.start()
	#initialize surfaces
	camera_surface = pygame.surface.Surface(CAMERA_SIZE, 0, screen)
	chat_surface = ChatSurface((400, SIZE[1]), leckerli_font, anon_font, anon_font_bold)
	print chat_surface.lines
	capture = True
	while capture:
		#get camera image
		camera_surface = camera.get_image(camera_surface)
		#draw the screen elements
		pygame.draw.rect(screen, DARK, [0, 0, SIZE[0], SIZE[1]])				#background color
		screen.blit(pygame.transform.scale(camera_surface, SIZE), (0,0))										#camera screen
		chat_surface.draw(screen)
		#flip the display buffers thus updating the surface
		pygame.display.flip()
		#handle events
		for event in pygame.event.get():
			if event.type == QUIT or (event.type == KEYDOWN and event.key == K_q):
				capture = False
			elif event.type == KEYDOWN and event.key == K_s:
				pygame.image.save(camera_surface, FILENAME)
	#die
	chat_surface.stop()
	camera.stop()
	pygame.quit()
# INIT CAMERA
if picamera_available == True:
    # Initialize camera with picamera library
    print "Initializing Rasberry Pi Camera"
    camera = picamera.PiCamera()
    camera.vflip = False 
    camera.hflip = False
    camera.brightness = 60
    camera.rotation = 90
else:
    print "Initializing Native Linux Camera"
    pygame.camera.init()
    cameras = pygame.camera.list_cameras()
    print ("Using camera " + cameras[0])
    camera = pygame.camera.Camera(cameras[0],(WIDTH, HEIGHT))
    camera.start()
    
screen = pygame.display.set_mode( ( WIDTH, HEIGHT ), pygame.NOFRAME )
pygame.display.set_caption("pyGame Camera View")
black = pygame.Color(0, 0, 0)
textcol = pygame.Color(255, 255, 0)
screen.fill(black)

# Open the photobooth background image
in_bgimage = PIL.Image.open("./photo_template.jpg")

#Cleanup GPIO settings
def cleanup():
    if (rpi_gpio_available == True):
        print('Cleaning up GPIO')
        GPIO.cleanup()
	def startCamera(self):
		global camera
		camera.start()
Example #40
0
 def on_startup(self):
     """Start the camera and return the camera instance"""
     pygame.camera.init()
     self.camera = camera = pygame.camera.Camera(pygame.camera.list_cameras()[0])
     camera.start()
     self.log.debug('camera started')