Commit 7b48f0a4 authored by Michael Murtaugh's avatar Michael Murtaugh

code

parents
apt get install python-opencv
pip install imutils picamera python-escpos
This diff is collapsed.
from __future__ import print_function
from escpos.printer import Usb
from urllib2 import urlopen
from PIL import Image
import sys
from escpos.exceptions import USBNotFoundError
import usb.core
from time import sleep
# 0416:5011
# brendan's
USB1 = 0x0416
USB2 = 0x5011
# citizen
# USB1 = 0x2730
# USB2 = 0x2002
""" Seiko Epson Corp. Receipt Printer M129 Definitions (EPSON TM-T88IV) """
# def wget (f, path):
# bytes = 0
# with open(path, "wb") as fout:
# while True:
# data = f.read(102400)
# if not data:
# break
# bytes += len(data)
# fout.write(data)
# print ("wget: {0} bytes to {1}".format(bytes, path), file=sys.stderr)
# return bytes
# def save_file(f):
# i = f.info()
# ct = i.get("Content-type")
# print ("content-type", ct)
# if ct.startswith("image/jpeg"):
# ext = ".jpg"
# else:
# ext = ".png"
# fpath = "tmp"+ext
# if wget(f, fpath):
# return fpath
def centered_text (text, width=32):
lines = []
for line in text.splitlines():
text = line.strip()[:width]
l = len(text)
mw = (width-l)/2
lines.append(" "*mw + text)
return "\n".join(lines)
def print_photostrip(data, copies=1):
try:
p = Usb(USB1,USB2,0)
# citizen
# p = Usb(USB1,USB2,0,0x81,0x02)
for copy in range(copies):
print ("printing copy {0}".format(copy+1))
for i in data['items']:
if "text" in i:
p.text(centered_text(i['text'])+"\n")
# p.text(i['text']+"\n")
# p.image(path)
# p.image("00001Tris.400x.dither.png")
elif "imagef" in i:
f = open(i['imagef'])
im = Image.open(f)
p.image(im)
elif "url" in i:
# p.text(centered_text(i['url']))
p.text(i['url']+"\n")
# if copy+1 < copies:
# p.text("--------------------------------")
p.cut()
if copy+1 == copies:
# extra space at the end
p.cut()
return True
except USBNotFoundError as e:
print ("Exception", e)
return False
except usb.core.USBError as e:
print ("Exception", e)
return False
except Exception as e:
print ("Exception", e)
return False
#p.text("Hello World\n")
# p.image("00001Tris.400x.jpg")
#p.image("00001Tris.400x.dither.png")
#p.text("\n")
#p.qr(content="http://recognitionmachine.constantvzw.org/p/1234567890/")
#p.text("\n")
#p.image("qr.test.png")
# p.barcode('1324354657687','EAN13',64,2,'','')
#p.cut()
def print_image (path, rotate):
try:
p = Usb(USB1,USB2,0)
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()
return True
except USBNotFoundError:
return False
# if __name__ == "__main__":
# import argparse
# ap = argparse.ArgumentParser("")
# ap.add_argument("--rotate", action="store_true", default=False)
# ap.add_argument("path", nargs="+")
# args = ap.parse_args()
# for n in args.path:
# print_image(n, rotate=args.rotate)
\ No newline at end of file
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
# 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
import RPi.GPIO as gpio
gpio.output(4, gpio.HIGH)
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)
ap.add_argument("--serial", default="/dev/ttyS0")
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)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment