simplephotobooth.py 7.07 KB
Newer Older
Michael Murtaugh's avatar
code  
Michael Murtaugh committed
1 2 3 4 5 6 7 8 9
from __future__ import print_function, division
from imutils.video import VideoStream
import datetime
import argparse
import os, sys
import cv2
from PIL import Image, ImageOps
# from escpos.exceptions import USBNotFoundError
from escpos.printer import Usb, Serial
Michael Murtaugh's avatar
Michael Murtaugh committed
10
from time import sleep
Michael Murtaugh's avatar
code  
Michael Murtaugh committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138


# brendan's
USB1 = 0x0416
USB2 = 0x5011

def take_photo(camera, rotate, width, height, sleept=2.0, iso=0):
    print ("take photo", file=sys.stderr)
    if camera == -1:
        import picamera, picamera.array
        with picamera.PiCamera(resolution=(width, height)) as camera:
            # camera.resolution = ()
            # camera.iso = iso
            if sleept:
                # print ("sleep", sleep, file=sys.stderr)
                sleep(sleept)
            #ss = camera.exposure_speed
            #camera.shutter_speed = ss
            #camera.exposure_mode = 'off'
            #g = camera.awb_gains
            #camera.awb_mode = 'off'
            #camera.awb_gains = g

            with picamera.array.PiRGBArray(camera) as frame:
                camera.capture(frame, 'bgr')
                # print("got frame", frame)
                current_image_bgr = frame.array
                gray = cv2.cvtColor(current_image_bgr, cv2.COLOR_BGR2GRAY)
                if rotate:
                    gray = imutils.rotate_bound(gray, rotate)
                    current_image_bgr = imutils.rotate_bound(current_image_bgr, rotate)
                else:
                    current_image_bgr = imutils.rotate_bound(current_image_bgr, 0)
                current_image = gray
                # print('Captured %dx%d image' % (
                #         output.array.shape[1], output.array.shape[0]))
                # _, imdata = cv2.imencode(".jpg", gray)
                # data["height"], data["width"] = gray.shape[:2]
                # data["image"] = make_jpeg_data_url(imdata)
                # emit("photo", data)
                # return jsonify(data)
                return current_image, current_image_bgr
    else:
        stream = cv2.VideoCapture(camera)
        (grabbed, frame) = stream.read()
        current_image_bgr = frame
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        if rotate:
            gray = imutils.rotate_bound(gray, rotate)
            current_image_bgr = imutils.rotate_bound(current_image_bgr, rotate)
        current_image = gray
        _, imdata = cv2.imencode(".jpg", gray)
        # data={}
        # data["height"], data["width"] = gray.shape[:2]
        # data["image"] = make_jpeg_data_url(imdata)
        # emit("photo", data)
        stream.release()
        return current_image, current_image_bgr

def get_faces (face_cascade, current_image, scaleFactor=None, minNeighbors=None, minSize=100):
    args = dict()
    if scaleFactor:
        args['scaleFactor'] = scaleFactor
    if minNeighbors:
        args['minNeighbors'] = minNeighbors
    if minSize:
        args['minSize'] = (minSize, minSize)
    gray = current_image
    faces = face_cascade.detectMultiScale(gray, **args)
    ret=[]
    for rect in faces:
        x, y, w, h = rect
        d = {'x': int(x), 'y': int(y), 'width': int(w), 'height': int(h)}
        ret.append(d)
    return ret

def fit_size (im, box):
    bw, bh = box
    iw, ih = im.size
    w = bw
    h = int((ih/iw) * w)
    if h <= bh:
        return (w, h)
    h = bh
    w = int((iw/ih) * h)
    return (w, h)

def make_print_version(im):
    im = im.convert("L")
    rw, rh = fit_size(im, (400, 10000))
    print ("rw, rh", rw, rh)
    im = im.resize((rw, rh), resample=Image.BICUBIC) # Image.BICUBIC

    im = ImageOps.equalize(im)
    im = im.convert("1")
    return im

def print_image (path, rotate=False):
    try:
        if args.usb:
            p = Usb(USB1,USB2) #, 0
        else:
            p = Serial(args.serial, args.baud)
        if path.startswith("http"):
            f = urlopen(i['image'])
            im = Image.open(f)
        else:
            im = Image.open(path)
        if rotate:
            im = im.rotate(90)
        p.image(im)
        p.cut()
        # p.text("\n"*2)
        return True
    except USBNotFoundError:
        return False



ap = argparse.ArgumentParser("")
ap.add_argument("--camera", type=int, default=-1)
ap.add_argument("--width", type=int, default=640)
ap.add_argument("--height", type=int, default=480)
ap.add_argument("--rotate", type=int, default=0)
ap.add_argument("--vflip", default=False, action="store_true")
ap.add_argument("--models", default="./models", help="location of the cascade XML files, default: ./models")
ap.add_argument('--gpiobutton', type=int, default=None, help="use given gpio pin as button")
ap.add_argument('--usb', action="store_true", default=False)
Michael Murtaugh's avatar
Michael Murtaugh committed
139
ap.add_argument("--serial", default="/dev/serial0")
Michael Murtaugh's avatar
code  
Michael Murtaugh committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
ap.add_argument("--baud", default=19200)
#ap.add_argument("--baud", default=19200)
# escpos.printer.Serial(devfile=u'/dev/ttyS0', baudrate=9600, bytesize=8, timeout=1, parity='N', stopbits=1, xonxoff=False, dsrdtr=True, *args, **kwargs)

args = ap.parse_args()
MODELS = os.path.expanduser(args.models)

os.system("mkdir -p images")

if args.gpiobutton:
    import RPi.GPIO as GPIO

    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    # LIGHT
    # GPIO.setup(4, GPIO.OUT)
    GPIO.setup(19, GPIO.OUT)  #BUTTONLED
    # BUTTON
    GPIO.setup(args.gpiobutton, GPIO.IN, pull_up_down=GPIO.PUD_UP)#Button to GPIO23

face_cascade = cv2.CascadeClassifier(os.path.join(MODELS, 'haarcascade_frontalface_default.xml'))

def wait_for_button(pin):
    while True:
        button_state = GPIO.input(args.gpiobutton)
        if button_state == False:
            return True
        sleep(0.1)

while True:
    if args.gpiobutton:
        GPIO.output(19, True)
        wait_for_button(args.gpiobutton)
        GPIO.output(19, False)
    else:
        raw_input("Press THE BUTTON to take a photo")

    current_image, current_image_bgr = take_photo(args.camera, args.rotate, args.width, args.height)
    current_faces = get_faces(face_cascade, current_image_bgr)
    n = datetime.datetime.now()
    base = n.strftime("%Y%m%d_%H%M%S")
    print (datetime.datetime.now())
    print ("detected {0} faces".format(len(current_faces)))

    image_fname = os.path.join("images", base + ".jpg")
    cv2.imwrite(image_fname, current_image)
    print ("image saved to {0}".format(image_fname), file=sys.stderr)

    for i, face in enumerate(current_faces):
        # cv2.imwrite("image.jpg", current_image)
        # fr = face['rect']
        ## fr = current_faces[0]['rect']
        # x1, y1, x2, y2 = fr.left(), fr.top(), fr.right(), fr.bottom()
        x, y, width, height = face['x'], face['y'], face['width'], face['height']
        x1, y1, x2, y2 = x, y, x+width, y+height
        current_face = current_image[y1:y2, x1:x2]
        current_face_bgr = current_image_bgr[y1:y2, x1:x2]

        fname = os.path.join("images", base+"_f{0}.jpg".format(i))
        # cv2.imwrite(fname, current_face)
        # print ("Face saved to {0}".format(fname), file=sys.stderr)

        current_face_pil = Image.fromarray(cv2.cvtColor(current_face_bgr,cv2.COLOR_BGR2RGB))
        current_face_pil = make_print_version(current_face_pil)
        current_face_pil.save(fname)
        print_image(fname)