def main(): hist = [] capture = cv2.VideoCapture('http://192.168.1.36:4746/mjpegfeed?1000x1080') # capture = cv2.VideoCapture(1) count = 0 while True: if cv2.waitKey(1) & 0xFF == ord('q'): break k = cv2.waitKey(10) ret, frame = capture.read() #frame = Zoom(frame, 1) resize = cv2.resize(frame, (700, 800)) #cv2.imshow('Current',resize) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) image = Image.fromarray(gray) width, height = image.size zbar_image = zbar.Image(width, height, 'Y800', image.tobytes()) scanner = zbar.ImageScanner() scanner.scan(zbar_image) for decoded in zbar_image: points = decoded.location print(decoded.data) if len(points) > 4: hull = cv2.convexHull( np.array([point for point in points], dtype=np.float32)) hull = list(map(tuple, np.squeeze(hull))) else: hull = points n = len(hull) for j in range(0, n): cv2.line(frame, hull[j], hull[(j + 1) % n], (255, 0, 0), 3) frame = cv2.resize(frame, (800, 800)) frame2 = cv2.flip(frame, 1) blank_image = np.zeros((height, width, 3), np.uint8) blank_image = cv2.resize(blank_image, (1500 - 200 - 500, 1000)) cv2.imshow("Results", frame2) arr = [] for decoded in zbar_image: points = decoded.location ll = [point for point in points] # x1=min(1500-200-500-ll[0][0],ll[1][0],ll[2][0],ll[3][0])#top-left pt. is the leftmost of the 4 points # x2=max(1500-200-500-ll[0][0],ll[1][0],ll[2][0],ll[3][0])#bottom-right pt. is the rightmost of the 4 points # y1=min(1500-200-500-ll[0][1],ll[1][1],ll[2][1],ll[3][1])#top-left pt. is the uppermost of the 4 points # y2=max(1500-200-500-ll[0][1],ll[1][1],ll[2][1],ll[3][1])#bottom-right pt. is the lowermost of the 4 points #print("coordinates") #cv2.line(blank_image,(h1,h2),(1500-200-500-ll[0][0],ll[0][1]),(255,255,255),15) cv2.line(blank_image, (1500 - 200 - 500 - ll[0][0], ll[0][1]), (1500 - 200 - 500 - ll[1][0], ll[1][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 200 - 500 - ll[1][0], ll[1][1]), (1500 - 200 - 500 - ll[2][0], ll[2][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 200 - 500 - ll[2][0], ll[2][1]), (1500 - 200 - 500 - ll[3][0], ll[3][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 200 - 500 - ll[3][0], ll[3][1]), (1500 - 200 - 500 - ll[0][0], ll[0][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 200 - 500 - ll[0][0], ll[0][1]), (1500 - 200 - 500 - ll[2][0], ll[2][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 200 - 500 - ll[2][0], ll[2][1]), (1500 - 200 - 500 - ll[2][0], ll[2][1]), (0, 0, 255), 25) xa = ll[0][0] + ll[1][0] + ll[2][0] + ll[3][0] ya = ll[0][1] + ll[1][1] + ll[2][1] + ll[3][1] xa /= 4 ya /= 4 lx, ly = xa, ya lol = 1 for j in hist: lol += 1 if lol <= 2: lx = j[1] ly = j[2] continue #print('lowllal',decoded.data,j[0]) if decoded.data == j[0]: #print "yaaaa",j[1],j[2], cv2.line(blank_image, (1500 - 200 - 500 - lx, ly), (1500 - 200 - 500 - j[1], j[2]), (100, 30, 255), 10) lx = j[1] ly = j[2] arr.append((xa, ya)) hist += [[decoded.data, xa, ya]] print('lenggg', len(hist)) if len(hist) > 100: del hist[0] for j in arr: cv2.line(blank_image, (1500 - 200 - 500 - j[0], j[1]), (1500 - 200 - 500 - xa, ya), (0, 255, 255), 10) dist = math.sqrt((xa - j[0])**2 + (ya - j[1])**2) if dist > 0.1: cv2.putText(blank_image, "{0}".format(round(dist, 2)), (1500 - 200 - 500 - (xa + j[0]) / 2, (ya + j[1]) / 2 + 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0)) if len(hist) > 100: del hist[0] cv2.imshow("Output", blank_image)
import math import zbar from PIL import Image ser = serial.Serial(port="/dev/ttyAMA0", baudrate=4800, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1) # qr code vars ################## camera = PiCamera() scanner = zbar.ImageScanner() scanner.parse_config('enable') sizeQrCode = 22.0 # in cm de diagonaal van de qr qrCodeDiag = 675.0 # the diagonal of the qr in px distance = 50 # in cm in real life distfac = (distance / qrCodeDiag) # in cm/px de size moet ook in cm zijn # lidar vars #############################
def __init__(self): import zbar self.scanner = zbar.ImageScanner() self.scanner.parse_config('enable')
def setUp(self): self.scn = zbar.ImageScanner()
def main(): #note: multithreading is untested, if code no work, replace capture = WebcamVideoStream(src=0).start() prevID = 0 oldtime = 0 fixed_time = datetime.strptime("3:00:00.000000", "%H:%M:%S.%f") fixed_time2 = datetime.strptime("4:00:00.000000", "%H:%M:%S.%f") while True: current_time = datetime.strptime(str(datetime.today().time()), "%H:%M:%S.%f") #logout at 3am if (fixed_time < current_time and current_time > fixed_time2): #data.logout() pass else: pass # Breaks down the video into frames frame = capture.read() # Converts image to grayscale. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Uses PIL to convert the grayscale image into a ndary array that ZBar can understand. image = Image.fromarray(gray) width, height = image.size zbar_image = zbar.Image(width, height, 'Y800', image.tobytes()) # Scans the zbar image. scanner = zbar.ImageScanner() scanner.scan(zbar_image) # Prints data from image. for decoded in zbar_image: idnumber = decoded.data #if idnumber is not prevID, login if (idnumber != prevID): data.login(idnumber) oldtime = time.time() else: #if 5 minutes has passed, reset prevID if (time.time() - oldtime > 299): #reset variables prevID = 0 idnumber = 0 else: pass prevID = idnumber frame = cv2.flip(frame, 1) cv2.namedWindow('image', cv2.WINDOW_NORMAL) cv2.resizeWindow('image', 500, 390) cv2.rectangle(frame, (175, 150), (450, 350), (255, 0, 0), 3) cv2.imshow('image', frame) if cv2.waitKey(1) == 27: break # esc to quit
def __init__(self, **kwargs): super(ZBarCam, self).__init__(**kwargs) Clock.schedule_once(lambda dt: self._setup()) # creates a scanner used for detecting qrcode self.scanner = zbar.ImageScanner()
def scanqr(): Orders.Orders().loadOrder( ) #Sincronizza Ordini da FoglioGoogle->orders.txt timeout = 60 #Timeout time for QRCode scanning timeout_start = time.time() #Avvio Timer while time.time() < timeout_start + timeout: RGB.RGBClass() RGB.RGBClass.blue_on() RGB.RGBClass.red_off() RGB.RGBClass.green_off() # crea uno stream dati in memoria stream = io.BytesIO() # visualizzazione dello streaming della camera with picamera.PiCamera() as camera: camera.exposure_mode = 'auto' camera.preview_fullscreen = False # ridimensiono il preview per poter interrompere in caso di problemi camera.preview_window = (300, 200, 640, 480) camera.start_preview() sleep(1) # aumentare se si vuole inquadrare meglio camera.capture(stream, format='jpeg') # recupera tutto il flusso per creare l'immagine stream.seek(0) pil = Image.open(stream) # inizializza lo scan dell'immagine scanner = zbar.ImageScanner() # configura il lettore scanner.parse_config('enable') pil = pil.convert('L') width, height = pil.size # raw = pil.tostring() raw = pil.tobytes() # wrap dati della immagine image = zbar.Image(width, height, 'Y800', raw) # cerca un QRcode scanner.scan(image) # se la password corrisponde ed e' esatta for symbol in image: # if hashlib.sha256(password).hexdigest() == symbol.data: for order in OrderClassList.loadorders( ): #Carico e inizializzo classe da Orders.txt ''' TO SHOW + CMD CLICK ''' if (len(symbol.data) == 44): if Crypter.decode( symbol.data ) == order.SerialNumber or Crypter.decode( symbol.data) == '000-0000000-0000001': #Gestione SpecialKeyQRCode if (Crypter.decode( symbol.data) == '000-0000000-0000001'): order = 1 RGB.RGBClass.blue_off() RGB.RGBClass.green_on() ''' print Crypter.decode(symbol.data) print order.SerialNumber print len(symbol.data) ''' return order # strip Eliminato qui else: RGB.RGBClass.blue_off() RGB.RGBClass.red_pulse() else: RGB.RGBClass.blue_off() RGB.RGBClass.red_pulse() # pulisci e cancella del (image) return None
def get_qr_content(with_gui=False, manual_detect=False): detected = False camera.init() if not len(camera.list_cameras()): print("No camera detected!") sys.exit(-1) cam = camera.Camera(camera.list_cameras()[config.camera_number - 1]) size = cam.get_size() width, height = size if not manual_detect: sys.stdout.write("QR detection started, wait several seconds...") sys.stdout.flush() cam.start() if with_gui: screen = pygame.display.set_mode(cam.get_size()) pygame.display.set_caption("Check QR recognize") else: with_gui = True print("QR detection through GUI, press any key when green line flash") data = 0 while not detected: try: if manual_detect: qr = QR() qr.decode_webcam() data = qr.data else: img = cam.get_image() # we can use file buffer for recognition # pygame.image.save(img, "file.jpg") # pil_string_image = Image.open("file.jpg").convert('L').tostring() pygame_img = pygame.image.tostring(img, 'RGB', False) pil_string_image = Image.fromstring( 'RGB', size, pygame_img).convert('L').tostring() if with_gui: screen.blit(img, (0, 0)) pygame.display.flip() # display update zbar_image = zbar.Image(width, height, 'Y800', pil_string_image) scanner = zbar.ImageScanner() scanner.parse_config('enable') data = scanner.scan(zbar_image) sys.stdout.write('.') sys.stdout.flush() for qr in zbar_image: if data: "Additional QR recognized!" data = qr.data if data: print("\nRecognized: `{}`".format(data)) detected = True except Exception as e: print("Error! " + str(e)) pass finally: time.sleep(config.qr_scan_waiting) if not manual_detect: pygame.display.quit() cam.stop() return 0 if data == "NULL" else data
def getQRPosition (path): # create a reader scanner = zbar.ImageScanner() # configure the reader scanner.parse_config('enable') # obtain image data img = cv2.imread(path) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) pil = Image.open(path).convert('L') width, height = pil.size raw = pil.tobytes() # wrap image data image = zbar.Image(width, height, 'Y800', raw) # scan the image for barcodes scanner.scan(image) res=False # extract results for symbol in image: # do something useful with results print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data QRData=symbol.data topLeftCorners, bottomLeftCorners, bottomRightCorners, topRightCorners = [item for item in symbol.location] topLeftCorner=[[topLeftCorners[0],topLeftCorners[1]]] bottomLeftCorner=[[bottomLeftCorners[0],bottomLeftCorners[1]]] topRightCorner=[[topRightCorners[0],topRightCorners[1]]] bottomRightCorner=[[bottomRightCorners[0],bottomRightCorners[1]]] corners = np.asarray([bottomLeftCorner,bottomRightCorner,topLeftCorner,topRightCorner],dtype=np.float32) res=True if (res==False): print 'Not able to scan QR' return 0,0,0 exit(1) objp = np.zeros((2*2,3), np.float32) objp[:,:2] = np.mgrid[0:2,0:2].T.reshape(-1,2) # termination criteria criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) objpoints = [] # 3d point in real world space imgpoints = [] # 2d points in image plane. objpoints.append(objp) imgpoints.append(corners) ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None) retval,rvec,tvec = cv2.solvePnP(objp, corners, mtx, dist) a=np.zeros((4,4),np.float32) a[0:3,0:3],_ = cv2.Rodrigues(np.asarray(rvecs)) a[0:3,3]= np.transpose(np.asarray(tvecs)[0])[0] a[3,3]=1 ai = np.linalg.inv(a) return 1, QRData, ai[0:3,3] #axis = np.float32([[1,0,0], [0,1,0], [0,0,-1]]).reshape(-1,3) #def draw(img, corners, imgpts): # corner = tuple(corners[0].ravel()) # img = cv2.line(img, corner, tuple(imgpts[0].ravel()), (255,0,0), 5) # img = cv2.line(img, corner, tuple(imgpts[1].ravel()), (0,255,0), 5) # img = cv2.line(img, corner, tuple(imgpts[2].ravel()), (0,0,255), 5) # return img #imgpts, jac = cv2.projectPoints(axis, rvec, tvec, mtx, dist) #img = draw(img,corners,imgpts) #cv2.imwrite('res.jpg', img) # cv2.imwrite('res.jpg',img) # clean up del(image)
def detectQR(frame): """ Detects QR Codes with ZBar. Parameters ---------- frame : numpy.ndarray image captured from the camera. """ # Convert frame to BW and get its size frameGrey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # array with height, widht and channels size = frameGrey.shape # Convert image from OpenCV to ZBar imageZBar = zbar.Image(size[1], size[0], 'Y800', frameGrey.tobytes()) # Construct an scan object and detect all QRCodes at frame scan = zbar.ImageScanner() scan.scan(imageZBar) index = 1 for QRCode in imageZBar: # Save corners and label attached to every QR Code imageCorners = QRCode.location tag = QRCode.data if len(imageCorners) == 4: # IMAGE VALUES Qi_x = (float(imageCorners[0][0]+imageCorners[1][0]+imageCorners[2][0]+imageCorners[3][0]))/4.0 Qi_y = (float(imageCorners[0][1]+imageCorners[1][1]+imageCorners[2][1]+imageCorners[3][1]))/4.0 Oi = np.array([frame.shape[1]/2, frame.shape[0]/2]) Qi = np.array([Qi_x, Qi_y]) # center Ai = np.array([imageCorners[0][0], imageCorners[0][1]]) Bi = np.array([imageCorners[1][0], imageCorners[1][1]]) Di = np.array([imageCorners[3][0], imageCorners[3][1]]) displayPoints(frame,Oi,Qi) displayShape(frame,imageCorners) # REAL VALUES # Inicialite values for getting the coordinates from the tag pri = 1 fin = 0 coor = np.zeros(2) j = 0 for i in range(len(tag)): if tag[i] == "," or tag[i] == ")": fin = i coor[j] = float(tag[pri:fin]) pri = i+1 j = j+1 # Tag is normalized for getting real coordinates of the points Qr = np.array([coor[0]*0.01, coor[1]*0.01]) # center # LOCATION # 1. Calculate L ax = Oi[0]-Qi[0] ay = Oi[1]-Qi[1] L = math.sqrt(ax**2 + ay**2) # 2. Calculate vectors q_v = np.array([(Ai[0]-Bi[0]),(Ai[1]-Bi[1])]) p_v = np.array([(Di[0]-Ai[0]),(Di[1]-Ai[1])]) a_v = np.array([ax,ay]) y_v = np.array([(Oi[0]-Oi[0]),(100-Oi[1])]) Y_v = np.array([((Qi[0]+q_v[0])-Qi[0]),((Qi[1]+q_v[1])-Qi[1])]) X_v = np.array([((Qi[0]+p_v[0])-Qi[0]),((Qi[1]+p_v[1])-Qi[1])]) displayVectors(frame, Oi, Qi, q_v, p_v) # 3. Calculate alpha3 alpha3 = math.acos((np.dot(y_v, Y_v))/(mag(y_v)*mag(Y_v))) # 4. Calculate alpha1 alpha1 = math.acos((np.dot(a_v, Y_v))/(mag(a_v)*mag(Y_v))) # 5. Calculate alpha2 alpha2 = math.acos((np.dot(a_v, X_v))/(mag(a_v)*mag(X_v))) # 6. Calculate unit unitx = 1/fx unity = 1/fy # 7. Relative coordinates xCam = L*unitx*math.cos(alpha2) yCam = L*unity*math.cos(alpha1) thetaCam = alpha3 # 8. Global coordinates - same axis # xRob = xCam + Qr[0]*0.01 # yRob = yCam + Qr[1]*0.01 # thetaRob = thetaCam # # 8.Global coordinates - different axis beta_x = 0 #coor[2] beta_y = math.pi #coor[3] Qr = np.append(Qr, beta_x) Qr = np.append(Qr, beta_y) rot = np.array([[math.cos(Qr[2]), math.sin(Qr[2]), 0], [-math.sin(Qr[3]), math.cos(Qr[3]), 0], [0, 0, 1]]) posCam = np.array([[xCam],[yCam],[thetaCam]]) posQr =np.array([Qr[0], Qr[1], Qr[3]]) posRob = np.transpose(np.dot(rot,posCam))[0] + posQr print("-----Robot position QR {}-----------------------------------------------\n".format(index)) print("X: {} Y: {} theta: {}".format(posRob[0], posRob[1], posRob[2])) print("-----------------------------------------------------------------------\n") index += 1;
def scanQR(): # initialize camera interface camera = picamera.PiCamera() # # MAX_IMAGE_RESOLUTION required so preview field of view matches capture one. camera.resolution = camera.MAX_RESOLUTION # # position and size info camera.rotation = 0 camera.preview_fullscreen = False camera.preview_window = (0, 0, 323, 240) # x, y, width, height # # loop forever while True: todo = to_cam.get() to_cam.task_done() if todo == 'start': # start writing camera image to screen camera.start_preview() # loop = True print "camera thread: camera started by command" while loop: # Create an in-memory stream stream = io.BytesIO() # # jpeg to save memory, resize to make processing faster, use_video_port to not change modes camera.capture(stream, format='jpeg', resize=(1024, 768), use_video_port=True) # # Rewind the stream for reading stream.seek(0) # # create a reader scanner = zbar.ImageScanner() # # configure the reader scanner.parse_config('enable') # # obtain image data pil = Image.open(stream).convert('L') width, height = pil.size raw = pil.tostring() # # wrap image data image = zbar.Image(width, height, 'Y800', raw) # # scan the image for barcodes scanner.scan(image) # # extract results, send them for symbol in image.symbols: if str(symbol.type) == 'QRCODE': if from_cam.empty(): from_cam.put(str(symbol.data)) camera.stop_preview() loop = False print "camera thread: camera stopped by QR capture" break # stop if told if not to_cam.empty(): todo = to_cam.get() if todo == 'stop': camera.stop_preview() loop = False print "camera stopped by command" to_cam.task_done()
def scan(surface, matrix, x, y, width, height, btype="CODE128", kfill=False): x0, y0 = matrix.transform_point(x, y) x1, y1 = matrix.transform_point(x + width, y + height) # Bounding box ... x = min(x0, x1) y = min(y0, y1) width = max(x0, x1) - x height = max(y0, y1) - y x, y, width, height = int(x), int(y), int(width), int(height) # Round the width to multiple of 4 pixel, so that the stride will # be good ... hopefully width = width - width % 4 + 4 # a1 surface for kfill algorithm a1_surface = cairo.ImageSurface(cairo.FORMAT_A1, width, height) cr = cairo.Context(a1_surface) cr.set_operator(cairo.OPERATOR_SOURCE) cr.set_source_surface(surface, -x, -y) cr.paint() if kfill: pxpermm = (matrix[0] + matrix[3]) / 2 barwidth = pxpermm * defs.code128_barwidth barwidth = int(round(barwidth)) if barwidth <= 3: return if barwidth > 6: barwidth = 6 image.kfill_modified(a1_surface, barwidth) # zbar does not understand A1, but it can handle 8bit greyscale ... # We create an inverted A8 mask for zbar, which is the same as a greyscale # image. a8_surface = cairo.ImageSurface(cairo.FORMAT_A8, width, height) cr = cairo.Context(a8_surface) cr.set_source_rgba(1, 1, 1, 1) cr.set_operator(cairo.OPERATOR_SOURCE) cr.paint() cr.set_source_rgba(0, 0, 0, 0) cr.mask_surface(a1_surface, 0, 0) del cr a8_surface.flush() # Now we have pixel data that can be passed to zbar img = zbar.Image() img.format = "Y800" img.data = str(a8_surface.get_data()) img.height = height # Use the stride, it should be the same as width, but if it is not, then # it is saner to add a couple of junk pixels instead of getting weird # offsets and missing data. img.width = a8_surface.get_stride() scanner = zbar.ImageScanner() scanner.scan(img) result = None result_quality = -1 for symbol in scanner.results: # Ignore barcodes of the wrong type if str(symbol.type) != btype: continue # return the symbol with the highest quality if symbol.quality > result_quality: result = symbol.data result_quality = symbol.quality # The following can be used to look at the images #rgb_surface = cairo.ImageSurface(cairo.FORMAT_RGB24, width, height) #cr = cairo.Context(rgb_surface) #cr.set_source_rgba(1, 1, 1, 1) #cr.set_operator(cairo.OPERATOR_SOURCE) #cr.paint() #cr.set_source_rgba(0, 0, 0, 0) #cr.mask_surface(a1_surface, 0, 0) #rgb_surface.write_to_png("/tmp/barcode-%03i.png" % barcode) #barcode += 1 return result
def __init__(self, pub, cube): self.pub = pub self.cube = cube self.scanner = zbar.ImageScanner() self.scanner.parse_config('enable') self.symbols = []
def main(): hist = {} q = [] count = 0 capture = cv2.VideoCapture('http://192.168.169.3:4745/mjpegfeed?1000x1080') #capture = cv2.VideoCapture(1) #capture = cv2.VideoCapture('./vid2.mp4') count = 0 while True: if cv2.waitKey(1) & 0xFF == ord('q'): break ret, frame = capture.read() resize = cv2.resize(frame, (700, 800)) #cv2.imshow('Current',resize) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) image = Image.fromarray(gray) width, height = image.size zbar_image = zbar.Image(width, height, 'Y800', image.tobytes()) scanner = zbar.ImageScanner() scanner.scan(zbar_image) for decoded in zbar_image: points = decoded.location print(decoded.data) if len(points) > 4: hull = cv2.convexHull( np.array([point for point in points], dtype=np.float32)) hull = list(map(tuple, np.squeeze(hull))) else: hull = points n = len(hull) for j in range(0, n): cv2.line(frame, hull[j], hull[(j + 1) % n], (255, 0, 0), 3) frame = cv2.resize(frame, (800, 800)) frame2 = cv2.flip(frame, 1) blank_image = np.zeros((height, width, 3), np.uint8) blank_image = cv2.resize(blank_image, (800, 1000)) cv2.imshow("Results", frame2) arr = [] lll = {} abra = False for decoded in zbar_image: abra = True lll[decoded.data] = True points = decoded.location ll = [point for point in points] # x1=min(1500-500-200-ll[0][0],ll[1][0],ll[2][0],ll[3][0])#top-left pt. is the leftmost of the 4 points # x2=max(1500-500-200-ll[0][0],ll[1][0],ll[2][0],ll[3][0])#bottom-right pt. is the rightmost of the 4 points # y1=min(1500-500-200-ll[0][1],ll[1][1],ll[2][1],ll[3][1])#top-left pt. is the uppermost of the 4 points # y2=max(1500-500-200-ll[0][1],ll[1][1],ll[2][1],ll[3][1])#bottom-right pt. is the lowermost of the 4 points #print("coordinates") #cv2.line(blank_image,(h1,h2),(1500-500-200-ll[0][0],ll[0][1]),(255,255,255),15) try: cv2.line(blank_image, (1500 - 500 - 200 - ll[0][0], ll[0][1]), (1500 - 500 - 200 - ll[1][0], ll[1][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - 200 - ll[1][0], ll[1][1]), (1500 - 500 - 200 - ll[2][0], ll[2][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - 200 - ll[2][0], ll[2][1]), (1500 - 500 - 200 - ll[3][0], ll[3][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - 200 - ll[3][0], ll[3][1]), (1500 - 500 - 200 - ll[0][0], ll[0][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - 200 - ll[0][0], ll[0][1]), (1500 - 500 - 200 - ll[2][0], ll[2][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - 200 - ll[2][0], ll[2][1]), (1500 - 500 - 200 - ll[2][0], ll[2][1]), (0, 0, 255), 25) except: continue xa = ll[0][0] + ll[1][0] + ll[2][0] + ll[3][0] ya = ll[0][1] + ll[1][1] + ll[2][1] + ll[3][1] xa /= 4 ya /= 4 lx, ly = xa, ya lol = 1 try: #print(hist[decoded.data]) for j in range(2, len(hist[decoded.data])): lol += 1 if lol <= 2: lx = hist[decoded.data][j][0] ly = hist[decoded.data][j][1] continue #print('lowllal',decoded.data,j[0]) #print "yaaaa",hist[decoded.data][j],hist[decoded.data][j+1], cv2.line(blank_image, (1500 - 500 - 200 - lx, ly), (1500 - 500 - 200 - hist[decoded.data][j][0], hist[decoded.data][j][1]), (100, (30 + hist[decoded.data][j][1] + hist[decoded.data][j][0]) % 254, 255), 10) lx = hist[decoded.data][j][0] ly = hist[decoded.data][j][1] #print 'lo', lx, ly except: #print 'la',lx, ly cv2.line(blank_image, (1500 - 500 - 200 - lx, ly), (1500 - 500 - 200 - lx, ly), (100, 30, 255), 10) arr.append((xa, ya)) try: hist[decoded.data].append([xa, ya]) hist[decoded.data][0] = 0 hist[decoded.data][1] = decoded except: hist[decoded.data] = [0, decoded, [xa, ya]] #print('lenggg',len(hist)) if len(hist[decoded.data]) > 80: del hist[decoded.data][2] # for j in arr: # cv2.line(blank_image, (1500-500-200 - j[0], j[1]), (1500-500-200 - xa, ya), (0, 255, 255), 10) # dist=math.sqrt((xa-j[0])**2+(ya-j[1])**2) # if dist>0.1: # cv2.putText(blank_image, "{0}".format(round(dist,2)), (1500-500-200-(xa+j[0])/2, (ya+j[1])/2+5 ), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,0)) count += 1 for j in hist: if hist[j][0] > 0: q.append(hist[j][1]) for j in hist: try: hist[j][0] += 1 except: hist[j][0] = 1 for decoded in q: if abra == False: continue print('hissss', hist[decoded.data][0]) if hist[decoded.data][0] > 20: continue try: if lll[decoded.data]: continue except: pass points = decoded.location ll = [point for point in points] # x1=min(1500-500-200-ll[0][0],ll[1][0],ll[2][0],ll[3][0])#top-left pt. is the leftmost of the 4 points # x2=max(1500-500-200-ll[0][0],ll[1][0],ll[2][0],ll[3][0])#bottom-right pt. is the rightmost of the 4 points # y1=min(1500-500-200-ll[0][1],ll[1][1],ll[2][1],ll[3][1])#top-left pt. is the uppermost of the 4 points # y2=max(1500-500-200-ll[0][1],ll[1][1],ll[2][1],ll[3][1])#bottom-right pt. is the lowermost of the 4 points #print("coordinates") #cv2.line(blank_image,(h1,h2),(1500-500-200-ll[0][0],ll[0][1]),(255,255,255),15) try: cv2.line(blank_image, (1500 - 500 - 200 - ll[0][0], ll[0][1]), (1500 - 500 - 200 - ll[1][0], ll[1][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - 200 - ll[1][0], ll[1][1]), (1500 - 500 - 200 - ll[2][0], ll[2][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - 200 - ll[2][0], ll[2][1]), (1500 - 500 - 200 - ll[3][0], ll[3][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - 200 - ll[3][0], ll[3][1]), (1500 - 500 - 200 - ll[0][0], ll[0][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - 200 - ll[0][0], ll[0][1]), (1500 - 500 - 200 - ll[2][0], ll[2][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - 200 - ll[2][0], ll[2][1]), (1500 - 500 - 200 - ll[2][0], ll[2][1]), (0, 0, 255), 25) except: continue xa = ll[0][0] + ll[1][0] + ll[2][0] + ll[3][0] ya = ll[0][1] + ll[1][1] + ll[2][1] + ll[3][1] xa /= 4 ya /= 4 lx, ly = xa, ya lol = 1 try: #print(hist[decoded.data]) for j in range(2, len(hist[decoded.data])): lol += 1 if lol <= 2: lx = hist[decoded.data][j][0] ly = hist[decoded.data][j][1] continue #print('lowllal',decoded.data,j[0]) #print "yaaaa",hist[decoded.data][j],hist[decoded.data][j+1], cv2.line(blank_image, (1500 - 500 - 200 - lx, ly), (1500 - 500 - 200 - hist[decoded.data][j][0], hist[decoded.data][j][1]), (100, (30 + hist[decoded.data][j][1] + hist[decoded.data][j][0]) % 254, 255), 10) lx = hist[decoded.data][j][0] ly = hist[decoded.data][j][1] #print 'lo', lx, ly except: #print 'la',lx, ly cv2.line(blank_image, (1500 - 500 - 200 - lx, ly), (1500 - 500 - 200 - lx, ly), (100, 30, 255), 10) arr.append((xa, ya)) try: hist[decoded.data].append([xa, ya]) hist[decoded.data][0] += 1 hist[decoded.data][1] = decoded except: hist[decoded.data] = [1, decoded, [xa, ya]] #print('lenggg',len(hist)) if len(hist[decoded.data]) > 100: del hist[decoded.data][2] # for j in arr: # cv2.line(blank_image, (1500-500-200 - j[0], j[1]), (1500-500-200 - xa, ya), (0, 255, 255), 10) # dist=math.sqrt((xa-j[0])**2+(ya-j[1])**2) # if dist>0.1: # cv2.putText(blank_image, "{0}".format(round(dist,2)), (1500-500-200-(xa+j[0])/2, (ya+j[1])/2+5 ), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,0,0)) if count > 4: q = [] count = 0 cv2.imshow("Output", blank_image)
def MealApp(): global QRCode global isEaten while True: isEaten = 0 now = datetime.datetime.now() if (now.hour >= 16 and now.hour < 18) or ( now.hour >= 0 and now.hour <= 5) or (now.hour >= 4 and now.hour < 8): isQrDetected = False frame = MC.readCamera() cv2.rectangle(frame, (1200, 500), (500, 730), (100, 70, 0), -2) cv2.putText( frame, "Current Date : " + str(now.year) + "-" + str(now.month) + "-" + str(now.day), (550, 550), MC.font, 1, (70, 0, 100), 2) cv2.putText(frame, "BreakFast Eaten User : "******" Lunch Eaten User : "******" Dinner Eaten User : "******"Face Recognition Cafe Monitering System", frame) cv2.waitKey(1) if MC.isDetected == True: i = 0 while i < 10: frame = MC.readCamera() cv2.imshow("Face Recognition Cafe Monitering System", frame) cv2.waitKey(1) i = i + 1 blackImage = MC.blackImage cv2.rectangle(blackImage, (1200, 500), (500, 730), (100, 70, 0), -2) cv2.putText( frame, "Current Date : " + str(now.year) + "-" + str(now.month) + "-" + str(now.day), (550, 550), MC.font, 1, (70, 0, 100), 2) cv2.putText(blackImage, "BreakFast Eaten User : "******" Lunch Eaten User : "******" Dinner Eaten User : "******":" + str( now1.minute) + ":" + str(now1.second) cv2.putText(blackImage, 'Position Your QRCode Correctly', (750, 50), MC.font, 0.5, (70, 0, 100), 2) cv2.putText(blackImage, CurrTime, (1250, 50), MC.font, 0.5, (70, 0, 100), 2) if QRDetect == True: try: if int(QRCode) <= 0 and int(QRCode) >= 9999: QRDetect = False engine.say( 'You Entered Invalid Meal Card Code') engine.runAndWait() else: engine.say('Meal Card Detected') engine.runAndWait() except: QRDetect = False engine.say('You Entered Invalid Meal Card Code') engine.runAndWait() cv2.imshow("Face Recognition Cafe Monitering System", blackImage) cv2.waitKey(1) cv2.imshow("Face Recognition Cafe Monitering System", blackImage) cv2.waitKey(1) cv2.putText(blackImage, 'Position Your QRCode Correctly(' + QRCode + ')', (750, 50), MC.font, 0.5, (70, 0, 100), 2) isEaten = MC.checkUser(QRCode) if isEaten == 1 or isEaten == 2: cursor = db.cursor() sql = "SELECT * FROM cafeuser WHERE QrNum=" + QRCode cursor.execute(sql) db.commit() row = cursor.fetchone() cursor.close() mealType = MC.mealTypeCheck() if isEaten == 1: engine.say('Hello ' + row[1] + ' ' + row[2] + ' Have A Good ' + mealType) engine.runAndWait() else: engine.say(row[1] + ' ' + row[2] + ' You Are Cheating') engine.runAndWait() elif isEaten == 3: engine.say('You Have Stolen Other Persons Meal Card') engine.runAndWait() elif isEaten == 4: engine.say('You Are Using Invalid Meal Card') engine.runAndWait() elif isEaten == 5: engine.say( 'You Meal Card is Disabled Please ReEnabled it Again') engine.runAndWait() else: ImageNotOpened = cv2.imread("BlackImage.jpg") CurrTime = "Cafe is Closed " cv2.putText(ImageNotOpened, CurrTime, (300, 400), MC.font, 2, (25, 255, 255), 2) CurrTime = "Current Time " + str(now.hour) + ":" + str( now.minute) + ":" + str(now.second) cv2.putText(ImageNotOpened, CurrTime, (400, 500), MC.font, 2, (25, 255, 255), 2) MC.readCamera() if MC.isDetected == True: engine.say('Dear User The Cafe is Still Closed') engine.runAndWait() cv2.imshow("Face Recognition Cafe Monitering System", ImageNotOpened) cv2.waitKey(1)
def main(): aff = 0 ok = False #choisir ta cam pour filme capture = cv2.VideoCapture(0) while True: # pour quite le porgramme apuis sur q if cv2.waitKey(1) & 0xFF == ord('q'): break # metre limage de la video sur frame ret, frame = capture.read() # couvrire limage au grayscale. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Uses PIL to convert the grayscale image into a ndary array that ZBar can understand. image = Image.fromarray(gray) width, height = image.size zbar_image = zbar.Image(width, height, 'Y800', image.tobytes()) #scanner le zbar image scanner = zbar.ImageScanner() n = scanner.scan(zbar_image) if n > aff: aff += 1 ok = True elif n < aff: aff -= 1 # scan le qr code (afiche la couleur ver sur les alentoure du qr code) for decoded in zbar_image: #desin le rectoncle pour affiche le dessin p = numpy.array(decoded.location) cv2.line(frame, (p[0][0], p[0][1]), (p[1][0], p[1][1]), (0, 255, 0), 2, 8, 0) cv2.line(frame, (p[1][0], p[1][1]), (p[2][0], p[2][1]), (0, 255, 0), 2, 8, 0) cv2.line(frame, (p[2][0], p[2][1]), (p[3][0], p[3][1]), (0, 255, 0), 2, 8, 0) cv2.line(frame, (p[3][0], p[3][1]), (p[0][0], p[0][1]), (0, 255, 0), 2, 8, 0) #envoie le ficher au serveur avec le threds + print sur la console if ok: thread2 = images(zbar_image, ok) thread2.start() thread2.join() ok = False #for decoded in zbar_image: # if ok : # ok=False # data = decoded.data.split(' ') # datas={'fname':data[0], 'lname':data[1]} # thread=post2(datas) # thread.start() # thread.join() # print(data[0]) # print(data[1]) # affiche la video on coure cv2.imshow('Current', frame)
def __init__(self): self.scanner = zbar.ImageScanner() # configure the reader self.scanner.parse_config('enable')
def __init__(self, region): self.bar_region = region # create a bar reader self.scanner = zbar.ImageScanner() # configure the reader self.scanner.parse_config('enable')
def CheckPart(): #print "Scanning Start" timeOut = 0 while True: my_stream = io.BytesIO() if timeOut >= 7: return with picamera.PiCamera() as camera: camera.capture(my_stream, format='jpeg') timeOut = timeOut + 1 scanner = zbar.ImageScanner() scanner.parse_config('enable') my_stream.seek(0) pil = Image.open(my_stream).convert('L') width, height = pil.size raw = pil.tostring() dcdImg = zbar.Image(width, height, 'Y800', raw) scanner.scan(dcdImg) #print "QR Code Sencing" for symbol in dcdImg: #print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data #time.sleep(0.5) if symbol.data != None: try: primary_key = symbol.data.split(',')[0] user_email = symbol.data.split(',')[1] qrock_key = symbol.data.split(',')[2] except: primary_key = '' user_email = '' qrock_key = '' data = {} data['qrock_pk'] = primary_key data['serial_number'] = SERIALNUMBER data['user_email'] = user_email data['qrock_key'] = qrock_key while True: header = { "Content-type": "application/x-www-form-urlencoded", "x-access-token": tknValue[0] } #print header r = request.post("http://qrock.cafe24app.com/iot/select", headers=header, data=data) #print r.text jsonData = json.loads(r.text) #Exception Handling : success, fail #print jsonData[0][u'code'] if jsonData[0][u'code'] == "success": mtrAction(motOpen) return elif jsonData[0][u'code'] == "not-token": #print "token refresh" refreshTkn() elif jsonData[0][u'code'] == "fail": print "It's wrong code" for i in range(3): ledTurn([rgbR]) time.sleep(0.8) ledTurn(()) time.sleep(0.8) return
def main(): """ A simple function that captures webcam video utilizing OpenCV. The video is then broken down into frames which are constantly displayed. The frame is then converted to grayscale for better contrast. Afterwards, the image is transformed into a numpy array using PIL. This is needed to create zbar image. This zbar image is then scanned utilizing zbar's image scanner and will then print the decodeed message of any QR or bar code. To quit the program, press "q". :return: """ # Begin capturing video. You can modify what video source to use with VideoCapture's argument. It's currently set # to be your webcam. capture = cv2.VideoCapture(1) f=open('Drink_Data.txt','r') _items={ 'drink0001':0, 'drink0002':0, 'drink0003':0, 'drink0004':0, 'drink0005':0 } _items_time={ 'drink0001':time.time(), 'drink0002':time.time(), 'drink0003':time.time(), 'drink0004':time.time(), 'drink0005':time.time() } _items_sold={ 'drink0001':0, 'drink0002':0, 'drink0003':0, 'drink0004':0, 'drink0005':0 } Sold_Number=0 _sold_data=f.readline() print _sold_data for i in range(5): print _sold_data[i] if _sold_data[i]=='1': _items_sold['drink000'+chr(1+i+ord('0'))]=1 Sold_Number+=1 f.close() while True: # To quit this program press q. if cv2.waitKey(1) & 0xFF == ord('q'): break # Breaks down the video into frames ret, frame = capture.read() # Displays the current frame cv2.imshow('Current', frame) # Converts image to grayscale. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Uses PIL to convert the grayscale image into a ndary array that ZBar can understand. image = Image.fromarray(gray) width, height = image.size zbar_image = zbar.Image(width, height, 'Y800', image.tobytes()) # Scans the zbar image. scanner = zbar.ImageScanner() scanner.scan(zbar_image) # Prints data from image. cnt=0 decoded_code=[] for decoded in zbar_image: cnt+=1 decoded_code.append(decoded.data) #print(decoded.data) #print(cnt) # Set when does the program stops End_Point=0 for _dcode in decoded_code: for _ecode in End_Code: if _dcode==_ecode: End_Point=1 break if End_Point==1: break if End_Point==1: break # Update dictionary _items for i in _items: if _items_sold[i]==1: continue _check=0 for _dcode in decoded_code: if _items[i]>0 and i==_dcode: _items_time[i]=time.time() _check=1 continue if _items[i]==0 and i==_dcode: _items_time[i]=time.time() _items[i]=1 _check=1 if _items[i]==0 and _check==0: if time.time()-_items_time[i]>_sold_time: print 'Item',i,'sold out!' _items_sold[i]=1 Sold_Number+=1 f=open('Drink_Data.txt','w') ch='' for j in range(5): ch+=chr(ord('0')+_items_sold['drink000'+chr(1+j+ord('0'))]) f.write(ch) f.close() if _items[i]>0 and _check==0: _items[i]=0 if Sold_Number==len(_items_sold): print 'All items were sold!' break for i in _items: if _items_sold[i]==1: continue print i, _items[i]
def barcode(state): #����ͧ�������ҹ������ #scsound() while True: db = MySQLdb.connect(host='192.168.94.64', user='******', passwd='', db='test') ############################ ## ���ҧ��ͺ��㹡�����¡��ҹ������ ## cur = db.cursor() ############################ cur.execute("SELECT trackid FROM ems2") #���͡�ҹ������㹡����ҹ������ cap = cv2.VideoCapture(0) #��ҹ�Ҿ�ҡ���ͧ����� scanner = zbar.ImageScanner() #���ҧ��ͻ��㹡����ҹ������ scanner.parse_config('enable') while (cap.isOpened()): endp = True end = 0 ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #�ç������ pil = Image.fromarray(gray) width, height = pil.size raw = pil.tobytes() #�ŧ�Ҿ���������͵�Ǩ�Ѻ������ image = zbar.Image(width, height, 'Y800', raw) scanner.scan(image) #�ʡ��ç��ǹ����繺����� for symbol in image: print ' decoded', symbol.type, 'symbol', "'%s'" % symbol.data for row in cur.fetchall(): #��ҹ���ʺ����鴨ҡ�ҹ�����ŷ����� trackid = str(row[0]) if symbol.data == trackid: #���ʵç�Ѻ�ҹ������ print 'code is correct' cur.execute("DELETE FROM ems2 WHERE trackid = '" + trackid + "'") #ź���ʷ��ç�Ѻ�ҹ�������͡�ҡ���ҧ�����ҹ�� cur.execute( "UPDATE ems SET status=%s WHERE trackid=%s", ('recieved', trackid)) #�ѻവ������ʷ��ç�Ѻ���������Ѻ���� db.commit() end = 2 endp = False break if end == 0: #scasound() end = 1 break if end == 1: #����������١��ͧ LED ��ᴧ�С�о�Ժ �����觢�ͤ�����ҹ�Ź� msg = "package number is not correct" a = test(msg) a.send() blink(redf) endp = False break if end == 2: #������ʶ١��ͧ ��е٨��Դ�͡�������ͻԴ���觢�ͤ�����Ҿ�ʴص�������Ţ���Ѻ���� #crsound() msg = "package number " + str(symbol.data) + ' received' a = test(msg) openLockf() a.send() break cv2.imshow('img', img) key = cv2.waitKey(1) & 0xFF if key == ord('q'): break cur.close() db.close() cap.release() cv2.destroyAllWindows() if endp == False: break GPIO.output(redf, GPIO.LOW) state[0] = 1 #����¹��Ңͧ��������ͺ͡ʶҹ���Ҩ���������
def sendqrcode(lock): """ A simple function that captures webcam video utilizing OpenCV. The video is then broken down into frames which are constantly displayed. The frame is then converted to grayscale for better contrast. Afterwards, the image is transformed into a numpy array using PIL. This is needed to create zbar image. This zbar image is then scanned utilizing zbar's image scanner and will then print the decodeed message of any QR or bar code. To quit the program, press "q". :return: """ ser = serial.Serial("/dev/ttyS0", baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, writeTimeout=1, timeout=10, rtscts=False, dsrdtr=False, xonxoff=False) # Begin capturing video. You can modify what video source to use with VideoCapture's argument. It's currently set # to be your webcam. # capture = cv2.VideoCapture(0) while True: lock.acquire() try: # Breaks down the video into frames ret, img = video.read() # print("2 lock") finally: lock.release() # print("2 unlock") # Breaks down the video into frames # ret, frame = capture.read() # Displays the current frame # cv2.imshow('Current', frame) frame = cv2.resize(img, (640, 360)) # Converts image to grayscale. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Uses PIL to convert the grayscale image into a ndary array that ZBar can understand. image = Image.fromarray(gray) width, height = image.size zbar_image = zbar.Image(width, height, 'Y800', image.tobytes()) # Scans the zbar image. scanner = zbar.ImageScanner() scanner.scan(zbar_image) # Prints data from image. for decoded in zbar_image: print(decoded.data) cmd = (decoded.data) ser.write(cmd.encode('ascii')) time.sleep(1) # To quit this program press q. if cv2.waitKey(1) & 0xFF == ord('q'): break ser.close()
def setUp(self): self.scn = zbar.ImageScanner() self.image = zbar.Image(size[0], size[1], 'Y800', data)
def detectQR(frame): """ Detects QR Codes with ZBar. Parameters ---------- frame : numpy.ndarray image captured from the camera. """ # Convert frame to BW and get its size frameGrey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # array with height, widht and channels size = frameGrey.shape # Convert image from OpenCV to ZBar imageZBar = zbar.Image(size[1], size[0], 'Y800', frameGrey.tobytes()) # Construct an scan object and detect all QRCodes at frame scan = zbar.ImageScanner() scan.scan(imageZBar) for QRCode in imageZBar: # Save corners and label attached to every QR Code imageCorners = QRCode.location tag = QRCode.data # Inicialite values for getting the coordinates from the tag pri = 0 fin = 0 coor = [0] * 12 j = 0 for i in range(len(tag)): if (tag[i] == ","): fin = i coor[j] = tag[pri:fin] pri = i + 1 j = j + 1 # Tag is normalized for getting real coordinates of the points x1 = float(coor[0]) y1 = float(coor[1]) z1 = float(coor[2]) x2 = float(coor[3]) y2 = float(coor[4]) z2 = float(coor[5]) x3 = float(coor[6]) y3 = float(coor[7]) z3 = float(coor[8]) x4 = float(coor[9]) y4 = float(coor[10]) z4 = float(coor[11]) imageCornersNp = np.array(imageCorners, np.float32) realCorners = np.float32([[x1, y1, z1], [x2, y2, z2], [x3, y3, z3], [x4, y4, z4]]) if len(imageCorners) == 4: # Get corners and shape of the QR Code in the original frame displayShape(frame, imageCorners) # Get decodified data from the QR Code displayLabel(frame, imageCorners, realCorners) # Get angle of the QR Code # getRotation(frame, imageCorners) # Get distorsion angle of the QR Code getAngles(frame, imageCornersNp, realCorners)
def main(): hist = {} q = [] counter = 0 pts = deque(maxlen=args["buffer"]) #variables for QR_code Connection centres = [] qr_conn = [] qr_conn1 = [] ccc = None (dX, dY) = (0, 0) direction = "" conn = [] counti = 0 capture = cv2.VideoCapture( 'http://192.168.173.168:4745/mjpegfeed?1000x1080') #capture = cv2.VideoCapture(1) #capture = cv2.VideoCapture('vid2.mp4') count = 0 vs = capture while True: if cv2.waitKey(1) & 0xFF == ord('q'): break ret, frame = capture.read() resize = cv2.resize(frame, (700, 800)) # cv2.imshow('Current',resize) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) image = Image.fromarray(gray) width, height = image.size zbar_image = zbar.Image(width, height, 'Y800', image.tobytes()) scanner = zbar.ImageScanner() scanner.scan(zbar_image) if len(hist) < len(qr_conn): qr_conn = qr_conn[len(qr_conn) - 1 - (len(qr_conn) - len(hist)):len(qr_conn) - 1] if len(conn) < 1: cv2.line(frame, (0, 0), (0, 0), (30, 90, 235), 1) for l in range(len(conn) - 1): #print('lol ',tuple(hist[conn[l].data][-1]),tuple(hist[conn[l+1].data][-1])) cv2.line(frame, tuple(hist[conn[l].data][-1]), tuple(hist[conn[l + 1].data][-1]), (30, 90, 235), 5) #cv2.line(frame, tuple(hist[conn[l].data][-1]),tuple(hist[conn[l+1].data][-1]) , (255, 255, 255), 5) #if l==len(conn)-1: #cv2.line(frame, tuple(hist[conn[l+1].data][-1]), tuple(hist[conn[0].data][-1]), (30, 90, 235), 5) for decoded in zbar_image: points = decoded.location #print(decoded.data) if len(points) > 4: hull = cv2.convexHull( np.array([point for point in points], dtype=np.float32)) hull = list(map(tuple, np.squeeze(hull))) else: hull = points n = len(hull) #print(hull) try: c1 = hull[0][0] + hull[1][0] + hull[2][0] + hull[3][0] c2 = hull[0][1] + hull[1][1] + hull[2][1] + hull[3][1] c1 /= 4 c2 /= 4 except: continue for j in range(0, n): cv2.line(frame, hull[j], hull[(j + 1) % n], (255, 0, 0), 3) cv2.line(frame, (c1, c2), (c1, c2), (255, 255, 0), 3) # if (math.sqrt((xa - xb) ** 2 + (ya - yb) ** 2) < threshold): # cv2.circle(blank_image, (xa, ya), 20, (0, 255, 0), -1) # if (xa, ya) not in qr_conn: # qr_conn.append((xa, ya)) # # if (len(qr_conn) > 0): # cv2.line(blank_image, qr_conn[len(qr_conn) - 1], (xb, yb), (0, 255, 255), 5) # for i in range(0, len(qr_conn) - 1): # cv2.line(blank_image, qr_conn[i], qr_conn[i + 1], (0, 255, 255), 5) #Code For Connecting QR_Codes. #print ("center:",centres) #needs code for setting an adaptive threshold threshold = 110 #set an appropriate threshold for distance between finger and QRcentre if (ccc != None): center = ccc #print('yas') #For connection in Blank image xa, ya = c1, c2 ya = ya xb, yb = center xb = abs(980 - xb - 40) yb = (yb) cv2.circle(frame, (c1, c2), 5, (255, 0, 255), -1) #cv2.circle(frame,(xa,ya),10,(0, 255,0 ), -1) print('c2,c2', c1, " ", c2, "xb,yb", xb, " ", yb) print("distance:", math.sqrt((xa - xb)**2 + (ya - yb)**2)) if (math.sqrt((xa - xb)**2 + (ya - yb)**2) < threshold): cv2.circle(frame, (c1, c2), 20, (255, 0, 255), -1) conn.append(decoded) if (xa, ya) not in qr_conn: qr_conn.append((xa, ya)) print(qr_conn) # if(len(qr_conn)>0): # cv2.line(frame, qr_conn[len(qr_conn)-1], (xb,yb) , (30, 90, 235), 5) # for i in range(0,len(qr_conn)-1): # cv2.line(frame, qr_conn[i], qr_conn[i+1] , (30, 90, 235), 5) # #For connection in Real Time Video # for point in arr: # xa,ya=point # xa=xa # ya=ya # xb,yb=center # # cv2.circle(fframe,(c1,c2),10,(0, 255,0 ), -1) # #print("distance:",math.sqrt((xa-xb)**2+(ya-yb)**2)) # if(math.sqrt((xa-xb)**2+(ya-yb)**2)<threshold): # cv2.circle(fframe,(xa,ya),20,(0, 255,0 ), -1) # if (xa,ya) not in qr_conn1: # qr_conn1.append((xa,ya)) # # # # if(len(qr_conn1)>0): # cv2.line(fframe, qr_conn1[len(qr_conn1)-1], center , (0, 255, 255), 5) # for i in range(0,len(qr_conn1)-1): # cv2.line(fframe, qr_conn1[i], qr_conn1[i+1] , (0, 255, 255), 5) frame = cv2.resize(frame, (800, 800)) frame2 = frame blank_image = np.zeros((height, width, 3), np.uint8) blank_image = cv2.resize(blank_image, (800, 1000)) arr = [] lll = {} abra = False centresl = [] for decoded in zbar_image: abra = True lll[decoded.data] = True points = decoded.location #centresl.append(find_centre(points)) ll = [point for point in points] # x1=min(1500-500-ll[0][0],ll[1][0],ll[2][0],ll[3][0])#top-left pt. is the leftmost of the 4 points # x2=max(1500-500-ll[0][0],ll[1][0],ll[2][0],ll[3][0])#bottom-right pt. is the rightmost of the 4 points # y1=min(1500-500-ll[0][1],ll[1][1],ll[2][1],ll[3][1])#top-left pt. is the uppermost of the 4 points # y2=max(1500-500-ll[0][1],ll[1][1],ll[2][1],ll[3][1])#bottom-right pt. is the lowermost of the 4 points # print("coordinates") # cv2.line(blank_image,(h1,h2),(1500-500-ll[0][0],ll[0][1]),(255,255,255),15) try: cv2.line(blank_image, (1500 - 500 - ll[0][0], ll[0][1]), (1500 - 500 - ll[1][0], ll[1][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - ll[1][0], ll[1][1]), (1500 - 500 - ll[2][0], ll[2][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - ll[2][0], ll[2][1]), (1500 - 500 - ll[3][0], ll[3][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - ll[3][0], ll[3][1]), (1500 - 500 - ll[0][0], ll[0][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - ll[2][0], ll[2][1]), (1500 - 500 - ll[2][0], ll[2][1]), (0, 0, 255), 25) except: continue xa = ll[0][0] + ll[1][0] + ll[2][0] + ll[3][0] ya = ll[0][1] + ll[1][1] + ll[2][1] + ll[3][1] xa /= 4 ya /= 4 lx, ly = xa, ya lol = 1 try: # print(hist[decoded.data]) for j in range(2, len(hist[decoded.data])): lol += 1 if lol <= 2: lx = hist[decoded.data][j][0] ly = hist[decoded.data][j][1] continue # print('lowllal',decoded.data,j[0]) # print "yaaaa",hist[decoded.data][j],hist[decoded.data][j+1], cv2.line(blank_image, (1500 - 500 - lx, ly), (1500 - 500 - hist[decoded.data][j][0], hist[decoded.data][j][1]), (100, (30 + hist[decoded.data][j][1] + hist[decoded.data][j][0]) % 254, 255), 5) lx = hist[decoded.data][j][0] ly = hist[decoded.data][j][1] # print 'lo', lx, ly except: # print 'la',lx, ly cv2.line(blank_image, (1500 - 500 - lx, ly), (1500 - 500 - lx, ly), (100, 30, 255), 10) arr.append((xa, ya)) try: hist[decoded.data].append([xa, ya]) hist[decoded.data][0] = 0 hist[decoded.data][1] = decoded except: hist[decoded.data] = [0, decoded, [xa, ya]] # print('lenggg',len(hist)) if len(hist[decoded.data]) > 80: del hist[decoded.data][2] for j in arr: cv2.line(blank_image, (1500 - 500 - j[0], j[1]), (1500 - 500 - xa, ya), (0, 255, 255), 5) dist = math.sqrt((xa - j[0])**2 + (ya - j[1])**2) if dist > 0.1: cv2.putText(blank_image, "{0}".format(round(dist, 2)), (1500 - 500 - (xa + j[0]) / 2, (ya + j[1]) / 2 + 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0)) #print("Centres:",centres) count += 1 # if(len(arr)>=len(centres)): #centres=arr for j in hist: if hist[j][0] > 0: q.append(hist[j][1]) for j in hist: try: hist[j][0] += 1 except: hist[j][0] = 1 for decoded in q: if abra == False: continue #print('hissss', hist[decoded.data][0]) if hist[decoded.data][0] > 20: continue try: if lll[decoded.data]: continue except: pass points = decoded.location ll = [point for point in points] # x1=min(1500-500-ll[0][0],ll[1][0],ll[2][0],ll[3][0])#top-left pt. is the leftmost of the 4 points # x2=max(1500-500-ll[0][0],ll[1][0],ll[2][0],ll[3][0])#bottom-right pt. is the rightmost of the 4 points # y1=min(1500-500-ll[0][1],ll[1][1],ll[2][1],ll[3][1])#top-left pt. is the uppermost of the 4 points # y2=max(1500-500-ll[0][1],ll[1][1],ll[2][1],ll[3][1])#bottom-right pt. is the lowermost of the 4 points # print("coordinates") # cv2.line(blank_image,(h1,h2),(1500-500-ll[0][0],ll[0][1]),(255,255,255),15) try: cv2.line(blank_image, (1500 - 500 - ll[0][0], ll[0][1]), (1500 - 500 - ll[1][0], ll[1][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - ll[1][0], ll[1][1]), (1500 - 500 - ll[2][0], ll[2][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - ll[2][0], ll[2][1]), (1500 - 500 - ll[3][0], ll[3][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - ll[3][0], ll[3][1]), (1500 - 500 - ll[0][0], ll[0][1]), (255, 255, 255), 10) cv2.line(blank_image, (1500 - 500 - ll[2][0], ll[2][1]), (1500 - 500 - ll[2][0], ll[2][1]), (0, 0, 255), 25) except: continue xa = ll[0][0] + ll[1][0] + ll[2][0] + ll[3][0] ya = ll[0][1] + ll[1][1] + ll[2][1] + ll[3][1] xa /= 4 ya /= 4 # font = cv2.FONT_HERSHEY_SIMPLEX # cv2.putText(blank_image, decoded.data, (xa, ya), font, 2, (255, 255, 255), 2, cv2.LINE_AA) lx, ly = xa, ya lol = 1 try: # print(hist[decoded.data]) for j in range(2, len(hist[decoded.data])): lol += 1 if lol <= 2: lx = hist[decoded.data][j][0] ly = hist[decoded.data][j][1] continue # print('lowllal',decoded.data,j[0]) # print "yaaaa",hist[decoded.data][j],hist[decoded.data][j+1], cv2.line(blank_image, (1500 - 500 - lx, ly), (1500 - 500 - hist[decoded.data][j][0], hist[decoded.data][j][1]), (100, (30 + hist[decoded.data][j][1] + hist[decoded.data][j][0]) % 254, 255), 7) lx = hist[decoded.data][j][0] ly = hist[decoded.data][j][1] # print 'lo', lx, ly except: # print 'la',lx, ly cv2.line(blank_image, (1500 - 500 - lx, ly), (1500 - 500 - lx, ly), (100, 30, 255), 10) arr.append((xa, ya)) try: hist[decoded.data].append([xa, ya]) hist[decoded.data][0] += 1 hist[decoded.data][1] = decoded except: hist[decoded.data] = [1, decoded, [xa, ya]] # print('lenggg',len(hist)) if len(hist[decoded.data]) > 100: del hist[decoded.data][2] for j in arr: cv2.line(blank_image, (1500 - 500 - j[0], j[1]), (1500 - 500 - xa, ya), (0, 255, 255), 5) dist = math.sqrt((xa - j[0])**2 + (ya - j[1])**2) if dist > 0.1: cv2.putText(blank_image, "{0}".format(round(dist, 2)), (1500 - 500 - (xa + j[0]) / 2, (ya + j[1]) / 2 + 5), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0)) if count > 4: q = [] count = 0 fframe = frame2 fframe = fframe[1] if args.get("video", False) else fframe fframe = imutils.resize(fframe, width=800, height=1000) blurred = cv2.GaussianBlur(fframe, (11, 11), 0) hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV) hsv = cv2.flip(hsv, 1) fframe = cv2.flip(fframe, 1) mask = cv2.inRange(hsv, greenLower, greenUpper) mask = cv2.erode(mask, None, iterations=2) mask = cv2.dilate(mask, None, iterations=2) # find contours in the mask and initialize the current # (x, y) center of the ball cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if imutils.is_cv2() else cnts[1] center = None # only proceed if at least one contour was found if len(cnts) > 0: # find the largest contour in the mask, then use # it to compute the minimum enclosing circle and # centroid c = max(cnts, key=cv2.contourArea) ((x, y), radius) = cv2.minEnclosingCircle(c) M = cv2.moments(c) center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) ccc = center # only proceed if the radius meets a minimum size if radius > 10: # draw the circle and centroid on the fframe, # then update the list of tracked points cv2.circle(fframe, (int(x), int(y)), int(radius), (0, 255, 255), 2) cv2.circle(fframe, center, 5, (0, 0, 255), -1) pts.appendleft(center) #lololol # loop over the set of tracked points for i in np.arange(1, len(pts)): # if either of the tracked points are None, ignore # them if pts[i - 1] is None or pts[i] is None: continue # check to see if enough points have been accumulated in # the buffer if counter >= 10 and i == 1 and pts[-1] is not None: # compute the difference between the x and y # coordinates and re-initialize the direction # text variables dX = pts[-1][0] - pts[i][0] dY = pts[-1][1] - pts[i][1] (dirX, dirY) = ("", "") # ensure there is significant movement in the # x-direction if np.abs(dX) > 20: dirX = "East" if np.sign(dX) == 1 else "West" # ensure there is significant movement in the # y-direction if np.abs(dY) > 20: dirY = "North" if np.sign(dY) == 1 else "South" # handle when both directions are non-empty if dirX != "" and dirY != "": direction = "{}-{}".format(dirY, dirX) # otherwise, only one direction is non-empty else: direction = dirX if dirX != "" else dirY # otherwise, compute the thickness of the line and # draw the connecting lines thickness = int(np.sqrt(args["buffer"] / float(i + 1)) * 2.5) cv2.line(fframe, pts[i - 1], pts[i], (0, 0, 255), thickness) # show the movement deltas and the direction of movement on # the fframe cv2.putText(fframe, direction, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 0, 255), 3) cv2.putText(fframe, "dx: {}, dy: {}".format(dX, dY), (10, fframe.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1) # show the fframe to our screen and increment the fframe counter counter += 1 cv2.imshow("input", fframe) cv2.imshow("Output", blank_image)
def ProcessPage(paper): answers = [] #contains answers gray_paper = cv2.cvtColor(paper, cv2.COLOR_BGR2GRAY) #convert image to grayscale scanner = zbar.ImageScanner() scanner.parse_config('enable') pil = Image.fromarray(gray_paper).convert('L') width, height = pil.size try: raw = pil.tobytes() except AttributeError: raw = pil.tostring() image = zbar.Image(width, height, 'Y800', raw) result = scanner.scan(image) if result == 0: codes = None else: for symbol in image: pass # clean up del (image) # Assuming data is encoded in utf8 data = symbol.data.decode(u'utf-8') codes = data corners = FindCorners(paper) #find the corners of the bubbled area #if we can't find the markers, return an error if corners is None: return [-1], paper, [-1] #calculate dimensions for scaling dimensions = [corners[1][0] - corners[0][0], corners[2][1] - corners[0][1]] #iterate over test questions for k in range(0, 2): #columns for i in range(0, 25): #rows questions = [] for j in range(0, 5): #answers #coordinates of the answer bubble x1 = int((columns[k][0] + j * spacing[0] - radius * 1.5) * dimensions[0] + corners[0][0]) y1 = int((columns[k][1] + i * spacing[1] - radius) * dimensions[1] + corners[0][1]) x2 = int((columns[k][0] + j * spacing[0] + radius * 1.5) * dimensions[0] + corners[0][0]) y2 = int((columns[k][1] + i * spacing[1] + radius) * dimensions[1] + corners[0][1]) #draw rectangles around bubbles cv2.rectangle(paper, (x1, y1), (x2, y2), (255, 0, 0), thickness=1, lineType=8, shift=0) #crop answer bubble questions.append(gray_paper[y1:y2, x1:x2]) #find image means of the answer bubbles means = [] #coordinates to draw detected answer x1 = int((columns[k][0] - radius * 8) * dimensions[0] + corners[0][0]) y1 = int((columns[k][1] + i * spacing[1] + 0.5 * radius) * dimensions[1] + corners[0][1]) #calculate the image means for each bubble for question in questions: means.append(np.mean(question)) #sort by minimum mean; sort by the darkest bubble min_arg = np.argmin(means) min_val = means[min_arg] #find the second smallest mean means[min_arg] = 255 min_val2 = means[np.argmin(means)] #check if the two smallest values are close in value if min_val2 - min_val < test_sensitivity_epsilon: #if so, then the question has been double bubbled and is invalid min_arg = 5 #write the answer cv2.putText(paper, answer_choices[min_arg], (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 150, 0), 1) #append the answers to the array answers.append(answer_choices[min_arg]) #draw the name if found from the QR code if codes is not None: cv2.putText(paper, str(codes), (int(0.28 * dimensions[0]), int(0.125 * dimensions[1])), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 0), 1) else: codes = [-1] return answers, paper, codes
def find_barcode(img, do_zlib=True, zxing_path=""): """ **SUMMARY** This function requires zbar and the zbar python wrapper to be installed or zxing and the zxing python library. **ZBAR** To install please visit: http://zbar.sourceforge.net/ On Ubuntu Linux 12.04 or greater: sudo apt-get install python-zbar **ZXING** If you have the python-zxing library installed, you can find 2d and 1d barcodes in your image. These are returned as Barcode feature objects in a FeatureSet. The single parameter is the ZXing_path along with setting the do_zlib flag to False. You do not need the parameter if you don't have the ZXING_LIBRARY env parameter set. You can clone python-zxing at: http://github.com/oostendo/python-zxing **INSTALLING ZEBRA CROSSING** * Download the latest version of zebra crossing from: http://code.google.com/p/zxing/ * unpack the zip file where ever you see fit >>> cd zxing-x.x, where x.x is the version number of zebra crossing >>> ant -f core/build.xml >>> ant -f javase/build.xml This should build the library, but double check the readme * Get our helper library >>> git clone git://github.com/oostendo/python-zxing.git >>> cd python-zxing >>> python setup.py install * Our library does not have a setup file. You will need to add it to your path variables. On OSX/Linux use a text editor to modify your shell file (e.g. .bashrc) export ZXING_LIBRARY=<FULL PATH OF ZXING LIBRARY - (i.e. step 2)> for example: export ZXING_LIBRARY=/my/install/path/zxing-x.x/ On windows you will need to add these same variables to the system variable, e.g. http://www.computerhope.com/issues/ch000549.htm * On OSX/Linux source your shell rc file (e.g. source .bashrc). Windows users may need to restart. * Go grab some barcodes! .. Warning:: Users on OSX may see the following error: RuntimeWarning: tmpnam is a potential security risk to your program We are working to resolve this issue. For normal use this should not be a problem. **Returns** A :py:class:`FeatureSet` of :py:class:`Barcode` objects. If no barcodes are detected the method returns None. **EXAMPLE** >>> bc = cam.getImage() >>> barcodes = img.findBarcodes() >>> for b in barcodes: >>> b.draw() **SEE ALSO** :py:class:`FeatureSet` :py:class:`Barcode` """ if do_zlib: try: import zbar except: logger.warning('The zbar library is not installed, please ' 'install to read barcodes') return None #configure zbar scanner = zbar.ImageScanner() scanner.parse_config('enable') raw = img.get_pil().convert('L').tostring() width = img.width height = img.height # wrap image data image = zbar.Image(width, height, 'Y800', raw) # scan the image for barcodes scanner.scan(image) barcode = None # extract results for symbol in image: # do something useful with results barcode = symbol else: if not ZXING_ENABLED: logger.warn("Zebra Crossing (ZXing) Library not installed. " "Please see the release notes.") return None global _barcode_reader if not _barcode_reader: if not zxing_path: _barcode_reader = zxing.BarCodeReader() else: _barcode_reader = zxing.BarCodeReader(zxing_path) tmp_filename = os.tmpnam() + ".png" img.save(tmp_filename) barcode = _barcode_reader.decode(tmp_filename) os.unlink(tmp_filename) if barcode: f = Factory.Barcode(img, barcode) return FeatureSet([f]) else: return None
# -*- coding: utf-8 -*- """ Created on Fri Aug 23 11:46:29 2019 @author: Srivatsan """ import time import zbar cv2.namedWindow("camera", 1) capture = cv2.VideoCapture(0) i = 0 while True: set_zbar = zbar.ImageScanner() cv2.imshow("camera", img) cv2.imwrite('pic{:>05}.jpg'.format(i), img) if cv2.WaitKey(10) == 27: break i += 1
def face_track(): with picamera.PiCamera() as camera: camera.resolution = (640, 480) #time.sleep(2) first_image = True print("Start Motion Tracking ....") #frame_count = 0 #start_time = time.time() while (True): with picamera.array.PiRGBArray(camera) as stream: camera.capture(stream, format='bgr') camera.framerate = 30 camera.sharpness = 60 camera.contrast = 50 camera.brightness = 50 image = stream.array if first_image: face_cascade = cv2.CascadeClassifier( '/home/pi/New/SelfieLibrary/faces.xml') #Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) scanner = zbar.ImageScanner() scanner.parse_config('enable') #thresh = 70 #im_bw = cv2.threshold(gray, thresh, 255, cv2.THRESH_BINARY)[1] #width, height = my_stream.size raw = gray.tostring() cv2.imwrite("bw.jpg", gray) stream = zbar.Image(600, 400, 'Y800', raw) scanner.scan(stream) #Here connectivity of database con = None for symbol in stream: BookID = symbol.data #print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data print 'BookID found', '"%s"' % BookID #return Book #BookID = 123456 try: con = psycopg2.connect(database="testdb", user="******", password="******", host="127.0.0.1", port="5432") cur = con.cursor() cur.execute("SELECT * FROM BookD where Id = %s" % (BookID)) rows = cur.fetchall() for row in rows: print row #return row #con.commit() except psycopg2.DatabaseError, e: if con: con.rollback() print 'Error %s' % e sys.exit(1) finally: if con: con.close() #Look for faces in the image using the loaded cascade file faces = face_cascade.detectMultiScale(gray, 1.1, 5) distances = [] if window_on: #Draw a rectangle around every found face for (x, y, w, h) in faces: cv2.rectangle(image, (x, y), (x + w, y + h), (255, 255, 0), 2) #print "Found "+str(len(faces))+" face(s)" #if len(faces)>0 : cv2.imwrite( '/home/pi/New/SelfieLibrary/result.jpg', gray) print "Found " + str(len(faces)) + " face(s)" img = cv2.imread( '/home/pi/New/SelfieLibrary/result.jpg') crop_img = img[y:y + h, x:x + w] crop_img = cv2.resize(crop_img, (100, 100)) # NOTE: its img[y: y + h, x: x + w] and *not* img[x: x + w, y: y + h] cv2.imwrite( "/home/pi/New/SelfieLibrary/cropped/probe/cropped.png", crop_img) distances = learnsk.face_rec() print min(distances)[0] if int(min(distances)[0]) <= 1.77436551952e+58: cv2.putText(image, str(min(distances)[1]), (x - 100, y), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 250), 1, 1) if window_on: cv2.imshow('Movement Status', image) #Save the result image # Close Window if q pressed if cv2.waitKey(1) & 0xFF == ord('q'): #im = cv2.imread("/home/pi/New/cropped/cropped.jpg") #print type(im) cv2.destroyAllWindows() break
def scan_image(filename): ret = [] #print filename # create a reader # configure the reader scanner = zbar.ImageScanner() scanner.parse_config('enable') # obtain image data pil = Image.open(filename).convert('L') def from_pil(scanner,pil): ret = [] try: #pil = pil.convert('L') width, height = pil.size raw = pil.tobytes() # wrap image data image = zbar.Image(width, height, 'Y800', raw) # scan the image for barcodes scanner.scan(image) # extract results for symbol in image: # do something useful with results ret.append((symbol.type, symbol.data)) # clean up del image del raw except: pass return ret ct = "[" + threading.currentThread().getName() + "]" r = from_pil(scanner,pil) if len(r) > 0: ret += r print ct,filename,"Found: Normal" sharpen = True if sharpen: pil2 = pil #for i in xrange(0,9): pil2 = pil2.filter(ImageFilter.SHARPEN) r = from_pil(scanner,pil2) if len(r) > 0: ret += r print ct,filename,"Found: sharpen!" del pil2 enhancer = True if enhancer: pil2 = image_enhancer(pil) r = from_pil(scanner,pil2) if len(r) > 0: ret += r print ct,filename,"Found: enhanced!" del pil2 rotate = True if rotate: i = 0 for angle in xrange(1,181): pil3 = pil.rotate(angle, resample=Image.BICUBIC, expand=0) r = from_pil(scanner,pil3) if len(r) >0: ret += r print ct,filename,"Found: Rotated: %d" % angle i+=1 if i > 9: break del pil3 del scanner del pil return ret