def encuentraYFiltraBlobs(self,areaMin, areaMax, toleranciaWH, desviacionD, toleranciaLP, tipoDibujo): imagenBlobs = Image(self.rutaImagenTratada_Fase2).copy() blobs = imagenBlobs.findBlobs() self.todosLosCandidatos = blobs if blobs: blobs.image = imagenBlobs self.areaBlobs = blobs.area() blobs = self.filtroPorArea(blobs, areaMin, areaMax) self.numBlobsCandidatosPorArea = len(blobs) # Busca los blobs de forma circular , los blobs que pasan el filtro # se guardan en la lista self.articulaciones blobs = self.filtroPorForma(blobs, toleranciaWH, desviacionD, toleranciaLP) if tipoDibujo == 'blobs': self.dibujaBlobs(blobs) elif tipoDibujo == 'estructura': self.dibujaEstructura(imagenBlobs) # La imagen tratada tiene que ser guardada porque sino no funciona # la integracion con Tkinter imagenBlobs.save(self.rutaImagenBlobs) return Image(self.rutaImagenBlobs)
def take_raw_image(): log("take_raw_image()") if DEBUG: img = Image(TEMP_FOLDER_PATH + STATIC_IMAGE_NAME_PATTERN % randint(0, 8)) else: img = capture_camera_image() return img.toRGB()
def scale(self, img_path, scale): new_file_path = self.nfn('resized') img = Image(img_path) img = img.scale(scale) img.save(new_file_path) self.transformations.append(new_file_path) return new_file_path
def _findGalaxyBulgeBlobs(galaxy): img = galaxy.imageWithoutBackground graynp = img.getGrayNumpy() stretched = np.array(graynp, dtype=np.float32)*(255.0/graynp.max()) stretched = Image(stretched) return stretched.threshold(220).binarize().invert().findBlobs(minsize=4)
def getConvolvedImage(self, kern, rep, bias): ''' Return a simple cv compatiable 8bit greyscaled image that has had the specified kernel applied rep times with bias supplied''' conv = ds.convolveColourMap(kern, rep, bias) iE = Image(conv.transpose()) return iE.invert()
def send_email(percentage): import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEImage import MIMEImage from email.MIMEText import MIMEText # Prepare actual message msg = MIMEMultipart() msg['From'] = "*****@*****.**" # change to your mail msg['To'] = "*****@*****.**" # change to your mail msg['Subject'] = "RPi Camera Alarm!" imgcv = Image("image.jpg") imgcv.save("imagesend.jpg", quality=50) # reducing quality of the image for smaller size img1 = MIMEImage(open("imagesend.jpg", "rb").read(), _subtype="jpg") img1.add_header('Content-Disposition', 'attachment; filename="image.jpg"') msg.attach(img1) part = MIMEText('text', "plain") part.set_payload(("Raspberry Pi camera alarm activated with level {:f}" ).format(percentage)) msg.attach(part) try: server = smtplib.SMTP("mail.htnet.hr", 25) #change to your SMTP provider server.ehlo() server.starttls() server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() print 'Successfully sent the mail' except smtplib.SMTPException as e: print(e)
def connectToServerAndHandleConnection(): HOST = 'localhost' PORT = 9898 while True: try: sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect((HOST,PORT)) img_str = sock.recv(100000) nparr = np.fromstring(img_str, np.uint8) img_np = cv2.imdecode(nparr, cv2.CV_LOAD_IMAGE_COLOR) # cv2.IMREAD_COLOR in OpenCV 3.1 img_ipl = cv.CreateImageHeader((img_np.shape[1], img_np.shape[0]), cv.IPL_DEPTH_8U, 3) cv.SetData(img_ipl, img_np.tostring(), img_np.dtype.itemsize * 3 * img_np.shape[1]) image = Image(img_ipl) barcodes = image.findBarcode() stringOut = '[]\n' if barcodes != None: stringOut = '' for barcode in barcodes: stringOut += str([barcode.x,barcode.y,int(barcode.length()), int(barcode.width()), barcode.data]) + ';' stringOut = stringOut[:-1] stringOut += '\n' sock.send(stringOut) except: continue
def rotate(self, img_path, shoe_measurements): img = Image(img_path) new_file_path = self.nfn('rotated') img = img.rotate(shoe_measurements.toe_heel_angle(), point=shoe_measurements.cleat_length_intersection()) self.transformations.append(new_file_path) img.save(new_file_path) return new_file_path
def capture(self): count = 0 currentframes = [] self.framecount = self.framecount + 1 for c in self.cameras: img = "" if c.__class__.__name__ == "Kinect" and c._usedepth == 1: img = c.getDepth() elif c.__class__.__name__ == "Kinect" and c._usematrix == 1: mat = c.getDepthMatrix().transpose() img = Image(np.clip(mat - np.min(mat), 0, 255)) else: img = c.getImage() if self.config.cameras[0].has_key('crop'): img = img.crop(*self.config.cameras[0]['crop']) frame = M.Frame(capturetime = datetime.utcnow(), camera= self.config.cameras[count]['name']) frame.image = img currentframes.append(frame) while len(self.lastframes) > self.config.max_frames: self.lastframes.pop(0) # log.info('framecount is %s', len(self.lastframes)) # Session().redis.set("framecount", self.framecount) count = count + 1 self.lastframes.append(currentframes) return currentframes
def get_faces(image_path, api_mode=False, rescale_face_crop=0): """ Return a list of cropped faces given an image path :param image_path: Path to image :type image_path: str :param api_mode: If api_mode is True get_faces returns a list of found HaarFeatures :type api_mode: bool :returns: list of images """ original_image = Image(image_path) faces = original_image.findHaarFeatures(segment_face) if api_mode: return faces else: if rescale_face_crop: return [ original_image.crop( scale_bounding_box(face.boundingBox(), rescale_face_crop)) for face in faces ] else: return [face.crop() for face in faces]
def find(self): new_file_path = self.nfn('dot-blobs') img = Image(self.img_path) new_img = img.colorDistance((160, 255, 160)).invert().binarize( (200, 200, 200)).invert().erode(1) for blob in new_img.findBlobs(): print str(blob) + " --> " + str( self.chance_blob_is_an_ellipse(blob)) dots = sorted(new_img.findBlobs()[-5:], key=lambda blob: blob.centroid()[1]) for blob in dots: blob.draw() new_img.dl().circle(blob.centroid(), 5, Color.RED) centroids = map(lambda blob: blob.centroid(), dots) bottom_screws = sorted(centroids[2:4], key=lambda centroid: centroid[0]) shoe_measurements = ShoeMeasurements(self.shoe.left_or_right, centroids[0], centroids[1], bottom_screws[0], bottom_screws[1], centroids[4]) new_img = shoe_measurements.draw_on_img(new_img) new_img.save(new_file_path) return (new_file_path, shoe_measurements)
def center(filename): image = Image(filename) blobs = image.findBlobs() box = blobs[0].mBoundingBox x = box[0] + box[2] / 2. y = box[1] + box[3] / 2. return [x, y]
def line_blobs(id): cur = g.db.execute( 'SELECT id, x, y, width, height FROM blobs WHERE image=?', [id]) blobs = cur.fetchall() entries = [] img = Image("static\\img\\%d.jpg" % id) for i, entry in enumerate(blobs): blob = img.crop(entry[1], entry[2], entry[3], entry[4]) if blob and 'SK_MODEL' in app.config: if blob.height > blob.width: blob = blob.resize(h=app.config['PATCH_SIZE']) else: blob = blob.resize(w=app.config['PATCH_SIZE']) blob = blob.embiggen( (app.config['PATCH_SIZE'], app.config['PATCH_SIZE'])) np_img = blob.getGrayNumpy().transpose().reshape(-1) pred = labels.inverse_transform(sk_model.predict(np_img))[0] if app.config['DEBUG']: blob.save("tmp\\pic%d %s.jpg" % (i, pred)) entries.append( dict(x=entry[1], y=entry[2], width=entry[3], height=entry[4], pred=pred)) else: entries.append( dict(x=entry[1], y=entry[2], width=entry[3], height=entry[4])) return jsonify(blobs=entries)
def send_email(percentage): import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEImage import MIMEImage from email.MIMEText import MIMEText # Prepare actual message msg = MIMEMultipart() msg['From'] = "*****@*****.**" # change to your mail msg['To'] = "*****@*****.**" # change to your mail msg['Subject'] = "RPi Camera Alarm!" imgcv = Image("image.jpg") imgcv.save("imagesend.jpg", quality=50) # reducing quality of the image for smaller size img1 = MIMEImage(open("imagesend.jpg","rb").read(), _subtype="jpg") img1.add_header('Content-Disposition', 'attachment; filename="image.jpg"') msg.attach(img1) part = MIMEText('text', "plain") part.set_payload(("Raspberry Pi camera alarm activated with level {:f}").format(percentage)) msg.attach(part) try: server = smtplib.SMTP("mail.htnet.hr", 25) #change to your SMTP provider server.ehlo() server.starttls() server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() print 'Successfully sent the mail' except smtplib.SMTPException as e: print(e)
def update(self, dt): self.img = GameInstance().cam.getImage().flipHorizontal() hsv = self.img.toHSV() mask = cv2.inRange(hsv.getNumpy(), GameInstance().lower, GameInstance().upper) img2 = Image(source=mask) img2 = img2.erode(1) img2 = img2.dilate(2) blops = img2.findBlobs() if blops: largest = blops[-1] x, y = largest.centroid() y = self.size[1] - y self.movement_filter(numpy.array([x, y])) self.blob_coor[0] = x self.blob_coor[1] = y if self.last_pos[1] is not None: with self.game.canvas: kvColor(1, 1, 0) d = 10. # Ellipse(pos=(x - d / 2, self.blob_coor[1] - d / 2), size=(d, d)) Line(points=(self.last_pos[0][0], self.last_pos[0][1], self.last_pos[1][0], self.last_pos[1][1])) self.last_pos[0] = self.last_pos[1]
def ProcessPlateBarcode(fileName): from SimpleCV import Image import pdb timeStamp = ProcessTimeStamp(fileName) [fileNameNoExt, fileExtension] = ProcessFileNameExtension(fileName) # pdb.set_trace() img = Image(fileName) barcode = img.findBarcode() if barcode != None: if len(barcode[0].data) >= 2: plateID = barcode[0].data[0:-1] checkSum = barcode[0].data[-1] calculatedChecksum = GenerateCheckSum(plateID) if checkSum is not calculatedChecksum: print "Error in barcode check sum. File: " + fileName else: plateID = 'UNKNOWN' else: plateID = 'UNKNOWN' return [plateID, timeStamp, fileExtension]
def addText(fileName, text): image = Image(fileName) draw = DrawingLayer((IMAGE_WIDTH, IMAGE_HEIGHT)) draw.rectangle((8, 8), (121, 18), filled=True, color=Color.YELLOW) draw.setFontSize(20) draw.text(text, (10, 9), color=Color.BLUE) image.addDrawingLayer(draw) image.save(fileName)
def unwarp(img): # Remap donut to 360 format print xmap print ymap img = Image(img) output = cv2.remap(img.getNumpyCv2(), xmap, ymap, cv2.INTER_LINEAR) # Return unwarped image return output
def trataImagen(self): img = Image(self.rutaImagenReducida) result = img.colorDistance((self.ajustes.r, self.ajustes.g, self.ajustes.b)) result.save(self.rutaImagenTratada_Fase1) result = result.invert() result = result.binarize(float(self.ajustes.umbralBinarizado)).invert() result.save(self.rutaImagenTratada_Fase2)
def crop(): #Begin Processing image print ('Begin processing image...') fullImage = Image('test/image/expected/fullImage.jpg') hundreds = fullImage.crop(602, 239, 28, 63) hundreds = hundreds.binarize(65).invert() hundreds.save('test/image/actual/hundredsImage.jpg') print ('Hundreds place cropped, binarized, and saved')
def __init__(self, image_url, mask_url): self.position = (10, 10) self.last_position = (0, 0) self.draw_position = (0, 0) self.direction = "left" self.orig_image = Image(image_url) self.orig_mask = Image(mask_url).invert() self.draw_image = self.orig_image.copy() self.draw_mask = self.orig_mask.copy()
def correct_alignment(si, image_path): new_file_path = step_file_path(si, 'correct-alignment') img = Image(image_path) if (img.width > img.height): img.rotate(-90, fixed=False).save(new_file_path) else: img.save(new_file_path) si.step_outputs.append(new_file_path) return new_file_path
def getDepth(self): ''' Return a simple cv compatiable 8bit depth image ''' depth = ds.getDepthMap() np.clip(depth, 0, 2**10 - 1, depth) depth >>=2 depth = depth.astype(np.uint8) iD = Image(depth.transpose()) return iD.invert()
def getSimpleCVImage(self): """Grabs a frame from the camera and returns a SimpleCV image object.""" img = np.empty((self.vRes * self.hRes * 3), dtype=np.uint8) self.picam.capture(img, 'bgr', use_video_port=True) img = img.reshape((self.vRes, self.hRes, 3)) img = Image(img, colorSpace=ColorSpace.RGB) img = img.rotate90() img = img.flipVertical() return img
def getDepth(self): ''' Return a simple cv compatiable 8bit depth image ''' depth = ds.getDepthMap() np.clip(depth, 0, 2**10 - 1, depth) depth >>= 2 depth = depth.astype(np.uint8) iD = Image(depth.transpose()) return iD.invert()
def findFace(imgPath): img = Image(imgPath) faces = img.findHaarFeatures("face.xml") if faces is not None: #print("find faces!") return True else: #print("Don't find andy faces!") return False
def correct_alignment(self, img_path): new_file_path = self.nfn('correct-alignment') img = Image(img_path) if (img.width > img.height): img.rotate(-90, fixed=False).save(new_file_path) else: img.save(new_file_path) self.transformations.append(new_file_path) return new_file_path
def _join_areas(self, areas): w, h = self._bgr_frame.size() frame = Image((w, h), colorSpace = ColorSpace.GRAY) a1, a2, a3, a4 = areas frame = frame.blit(a1, pos=(0, 0)) frame = frame.blit(a2, pos=(int(w*self.SPLITS[0]), 0)) frame = frame.blit(a3, pos=(int(w*self.SPLITS[1]), 0)) frame = frame.blit(a4, pos=(int(w*self.SPLITS[2]), 0)) return frame
def trataImagen(self): img = Image(self.rutaImagenReducida) result = img.colorDistance( (self.ajustes.r, self.ajustes.g, self.ajustes.b)) result.save(self.rutaImagenTratada_Fase1) result = result.invert() result = result.binarize(float(self.ajustes.umbralBinarizado)).invert() result.save(self.rutaImagenTratada_Fase2)
def getConvolvedDepth(self, kern, rep, bias): ''' Return a simple cv compatiable 8bit depth map that has had the specified kernel applied rep times ''' conv = ds.convolveDepthMap(kern, rep, bias) np.clip(conv, 0, 2**10 - 1, conv) conv >>=2 conv = conv.astype(np.uint8) iE = Image(conv.transpose()) return iE.invert()
def test(): with timer('image'): img = Image('train/372.png') print "image size (%d, %d)" % img.size() with timer('parse'): p = parse_frame(img) print '--------------' return p
def trataImagen(self, r, g, b, umbralBinarizado): inicio = time.time() img = Image(self.rutaImagenReducida) result = img.colorDistance((r, g, b)).invert() result = result.binarize(umbralBinarizado).invert() result.save(self.rutaImagenTratada) fin = time.time() self.tiempoTratamiento = fin - inicio
def on_image(self, data): print 'Image Received' imgstr = re.search(r'base64,(.*)', data).group(1) #This is a hack to clean up the encoding. tempimg = StringIO.StringIO(imgstr.decode('base64')) pilimg = PILImage.open(tempimg) img = Image(pilimg) img = img.edges() pimg = img.getPIL() output = StringIO.StringIO() pimg.save(output, format='JPEG') sendstr = 'data:image/jpeg;base64,' + output.getvalue().encode('base64') self.emit('update', sendstr)
def blob(id): cur = g.db.execute("SELECT id, image, x, y, width, height FROM annotations WHERE annotations.id=?", [id]) line = cur.fetchone() img = Image("static\\img\\%d.jpg" % int(line[1])) blob = img.crop(line[2], line[3], line[4], line[5]) io = StringIO() blob.save(io) data = io.getvalue() resp = make_response(data) resp.content_type = "image/jpeg" return resp
def main(): camera = cv2.VideoCapture('video2.avi') background_subtractor = cv2.BackgroundSubtractorMOG() # Store previous tracking image previous_track_image = Image() while camera.isOpened(): is_success, image = camera.read() if is_success: mask = background_subtractor.apply(image, None, 0.1) # Vehicles will be detected from this image track_image = Image(ndimage.median_filter(mask, 3), cv2image=True) blobs = track_image.findBlobs(minsize=250, maxsize=800) if not blobs: # print('No Blobs Found.') continue else: # print("Width: {0}; Height: {1}".format(blobs[0].width(), blobs[0].height())) # Only keep near square blobs blobs = filter(lambda b: 0.25 < b.width() / b.height() < 4, blobs) # print("Found {0} Blobs. {1}".format(len(blobs))) if len(vehicle_track_set_list) == 0: # Find first batch of blobs for blob in blobs: blob.drawRect(color=Color.BLUE, width=3, alpha=225) # bounding_box = tuple(blob.boundingBox()) # print("Area: {0}".format(blob.area())) track_set = track_image.track(method='mftrack', img=track_image, bb=blob.boundingBox()) if track_set: vehicle_track_set_list.append(VehicleTrackSet(track_set)) track_set.drawBB(color=(255, 0, 0)) track_set.drawPath() track_image.show() else: for blob in blobs: blob.drawRect(color=Color.BLUE, width=3, alpha=225) # print("Blob Coordinate: ({0}, {1}).".format(blob.x, blob.y)) update_track_set(track_image, previous_track_image, blob.boundingBox()) # Save current image previous_track_image = track_image # time.sleep(0.1) else: camera.release() break
def take_background(): log("take_background()") # get background snapshot if DEBUG: img = Image(TEMP_FOLDER_PATH + STATIC_BACKGROUND_NAME) else: img = capture_camera_image() # get mean_color mean_color = img.meanColor() # save it db = db_open() db_backgrounds_write(db, db_background(date_created=datetime.now(), mean_color=mean_color)) db_close(db)
def edgify(in_full_path): (root, ext) = os.path.splitext(in_full_path) out_full_path = root + '_edgified' + ext img = Image(in_full_path) # create an edge image using the Canny edge detector # set the first threshold to 160 output = img.edges(t1=50, t2=50) # invert white on black image output = output.invert() # save the output images. output.save(out_full_path) return out_full_path
def findYellowMask(image_file): original = Image(image_file) yellow_only = original.colorDistance((232,166,30)) yellow_only = yellow_only*4 mask = yellow_only.invert() #mask.save("yellow_mask.jpg") binarizedMask = mask.binarize().invert() #binarizedMask.save("binarized_mask_yellow.jpg") return binarizedMask
def getImage(self): if isinstance(self._scv_cam, Kinect): if self._scv_cam._usedepth == 1: img = self._scv_cam.getDepth() elif self._scv_cam._usematrix == 1: mat = self._scv_cam.getDepthMatrix().transpose() img = Image(np.clip(mat - np.min(mat), 0, 255)) else: img = self._scv_cam.getImage() else: img = self._scv_cam.getImage() if self.crop: img = img.crop(self.crop) return img
def build_bg(): for n in range(BG_PICS): pn = bgname.format(n) save_picture(pn) sleep(FRAME_DELAY) camera.stop_preview() frames = ImageSet() frames.load(bgdir) img = Image(frames[0].size()) nframes = len(frames) for frame in frames: img = img + (frame / nframes) img.save(bgf) return img
def blob(id): cur = g.db.execute( 'SELECT id, image, x, y, width, height FROM annotations WHERE annotations.id=?', [id]) line = cur.fetchone() img = Image("static\\img\\%d.jpg" % int(line[1])) blob = img.crop(line[2], line[3], line[4], line[5]) io = StringIO() blob.save(io) data = io.getvalue() resp = make_response(data) resp.content_type = "image/jpeg" return resp
def on_image(self, data): print 'Image Received' imgstr = re.search(r'base64,(.*)', data).group( 1) #This is a hack to clean up the encoding. tempimg = StringIO.StringIO(imgstr.decode('base64')) pilimg = PILImage.open(tempimg) img = Image(pilimg) img = img.edges() pimg = img.getPIL() output = StringIO.StringIO() pimg.save(output, format='JPEG') sendstr = 'data:image/jpeg;base64,' + output.getvalue().encode( 'base64') self.emit('update', sendstr)
def query_blob(id): blob = Image("static\\img\\%d.jpg" % id).crop( int(request.form["x"]), int(request.form["y"]), int(request.form["width"]), int(request.form["height"]) ) if blob and "SK_MODEL" in app.config: if blob.height > blob.width: blob = blob.resize(h=app.config["PATCH_SIZE"]) else: blob = blob.resize(w=app.config["PATCH_SIZE"]) blob = blob.embiggen((app.config["PATCH_SIZE"], app.config["PATCH_SIZE"])) np_img = blob.getGrayNumpy().transpose().reshape(-1) pred = labels.inverse_transform(sk_model.predict(np_img))[0] return jsonify(prediction=pred) else: return jsonify(prediction="")
def update(self, dt): self.img = GameInstance().cam.getImage().flipHorizontal() GameInstance().lower = np.array((float(self.val[0]), float(self.val[1]), float(self.val[2]))) GameInstance().upper = np.array((float(self.val[3]), float(self.val[4]), float(self.val[5]))) hsv = self.img.toHSV() mask = cv2.inRange(hsv.getNumpy(), GameInstance().lower, GameInstance().upper) img2 = Image(source=mask) img2 = img2.erode(1) img2 = img2.dilate(2) if self.cvActiveBloops.active: blops = img2.findBlobs() if blops: self.cvBlob.texture = getKivyTexture(blops[-1].getMaskedImage()) self.cvFilter.texture = getKivyTexture(img2) self.cvImage.texture = getKivyTexture(self.img)
def test(): f = Features(**PARAMS) for i in range(300, 400): path = 'test/' + str(i) + '.png' im = Image(path) f.set_image(im) f.extract_blobs()
def getSensors(self): screenshot(PATH, REGION) im = Image(PATH) f.set_image(im) sensors = asarray(f.extract()) self.is_alive = sensors[2] return sensors
def test(): f = Features(**PARAMS) minx,maxx = 0,0 miny,maxy = 0,0 while True: path = 'test/tmp.png' screenshot(path, region=REGION) im = Image(path) f.set_image(im) blobs = f.extract_blobs() if not blobs[0]: break dl = f.small.dl() bottom_right_corner = blobs[0].bottomRightCorner() dl.circle(bottom_right_corner, 5, Color.RED) if blobs[1]: top_right = blobs[1].topRightCorner() x = bottom_right_corner[0] - top_right[0] y = bottom_right_corner[1] - top_right[1] if x < minx: minx = x elif x > maxx: maxx = x if y < miny: miny = y elif y > maxy: maxy = y dl.circle(top_right, 5, Color.RED) f.small.show() print 'minx, maxx', minx, maxx print 'miny, maxy', miny, maxy
def getBackground(self): """ **SUMMARY** Get Background of the Image. For more info read http://opencvpython.blogspot.in/2012/07/background-extraction-using-running.html **PARAMETERS** No Parameters **RETURNS** Image - SimpleCV.ImageClass.Image **EXAMPLE** >>> while (some_condition): ... img1 = cam.getImage() ... ts = img1.track("camshift", ts1, img, bb) ... img = img1 >>> ts.getBackground().show() """ from SimpleCV import Image imgs = self.trackImages(cv2_numpy=True) f = imgs[0] avg = np.float32(f) for img in imgs[1:]: f = img cv2.accumulateWeighted(f, avg, 0.01) res = cv2.convertScaleAbs(avg) return Image(res, cv2image=True)
def loadData(paths, classes): class_dict = generateDictOfClasses(classes) all_data = None for i in range(len(paths)): path = paths[i] print path for img in os.listdir(path): m = re.search('.*Thumbs\.(db)', img) # in windows XP, this is a problem if (m is None): img_path = path + "/" + img img_data = thresholdOp(Image(img_path)) flattened = img_data.getNumpy()[:, :, 1].flatten() # 25x20 (wxh) flattened[flattened == 255] = 1 # set every '255' to '1' if all_data is None: all_data = ClassificationDataSet(len(flattened), nb_classes=len(classes), class_labels=classes) all_data.addSample( flattened, [class_dict[classes[i]]]) # [data[1],data[2]] return all_data
def detect_digit(self, digit_image): """ Which digit is on the image ? """ detected_digits = [] # We don't reconize all digits yet for digit in [0, 1, 3, 4, 5, 6, 7, 8, 9]: template_image = Image("./images/digits/" + str(digit) + ".png").resize(w=digit_image.width, h=digit_image.height) diff_image = digit_image - template_image diff_index = diff_image.getNumpy().mean() detected_digits.append((digit, diff_index)) sorted_array = sorted(detected_digits, key=itemgetter(1)) detected_digit = sorted_array[0][0] logging.debug("Detected digit " + str(detected_digit)) return detected_digit
def feature_extractor(): #Abrir arquivo que vai receber as features dos arquivos de imagens file = "image_features_train_1.arff" text_file = open(file, "a") trainPath = "C:/Python27/ARP/Dataset/train2" dirList = os.listdir(trainPath) edge = EdgeHistogramFeatureExtractor(1) for dirName in dirList: fileList = os.listdir(trainPath + '/' + dirName) maxsize = len(fileList) for i in range(0, maxsize): #print fileList[i] filePATH = (trainPath + '/' + dirName + '/' + fileList[i]) img = Image(filePATH) #Feature - Edge histogram edge_vecs = edge.extract(img) edge_fields = edge.getFieldNames() for y in range(0, edge.getNumFields()): #print edge_fields[y], '=', edge_vecs[y] text_file.write(str(edge_vecs[y]) + ",") #Feature - Hue #hue = HueHistogramFeatureExtractor(10) #hue_vecs = hue.extract(img) #hue_fields = hue.getFieldNames() #for i in range(0, hue.getNumFields()): #print hue_fields[i], '=', hue_vecs[i] #text_file.write(str(hue_vecs[i]) + ",") text_file.write(dirName + "\n") text_file.close()
def predictor(): for img in glob('/home/linuxsagar/tempTest/*'): #List to hold the feature of new Image _new_features = [] #Read the test image _custom_image = Image(img) #Extract features _newHhfe = hhfe.extract(_custom_image) _newEhfe = ehfe.extract(_custom_image) _newHaarfe = haarfe.extract(_custom_image) #List for the graph hue_data = [] haar_data = [] edge_data = [] hue_fields = hhfe.getFieldNames() for i in range(0, hhfe.getNumFields()): hue_data.append(str(hue_fields[i]) + ' = ' + str(_newHhfe[i])) edge_fields = ehfe.getFieldNames() for i in range(0, hhfe.getNumFields()): edge_data.append(str(edge_fields[i]) + ' = ' + str(_newEhfe[i])) haar_fields = haarfe.getFieldNames() for i in range(0, len(haar_fields)): haar_data.append(str(haar_fields[i]) + ' = ' + str(_newHaarfe[i])) #Concatinate all feature to one _new_features.append(np.concatenate([_newHhfe, _newEhfe, _newHaarfe])) probability = np.amax(classifier.predict_proba(_new_features)) #Call method to generate histogram image make_histogram(_custom_image.histogram(), _newHhfe, _newEhfe, _newHaarfe, dataDir) #The Final result to view result = [ "The given input is classified as: {}.".format( classifier.predict(_new_features)[0]), "Probability of prediction: {:.1%}".format((probability)) ] return [result, hue_data, edge_data, haar_data]
def getSync(self): ''' Return a simplecv compatiable synced map with dimensions of the depth map and colours from the colour map. Indexes here match indexes in the vertex map ''' sync = ds.getSyncMap() sync = sync[:, :, ::-1] return Image(sync.transpose([1, 0, 2]))
def imageDifference(): if not os.path.isfile("image.jpg"): subprocess.call("raspistill -n -t 1 -w 640 -h 480 -e jpg -o image.jpg", shell=True) time.sleep(0.5) img = Image("image.jpg") time.sleep(0.2) subprocess.call("raspistill -n -t 1 -w 640 -h 480 -e jpg -o image.jpg", shell=True) img2 = Image("image.jpg") diffimg = img2 - img matrix = diffimg.getNumpy() flat = matrix.flatten() mean = matrix.mean() return mean
def getimage(x,y): """ 获取百度地图图片 """ nowtime=time.time() url='http://its.map.baidu.com:8002/traffic/TrafficTileService?time={0}&level=17&x={1}&y={2}'.format(nowtime,x,y) try: try: img=Image(url) except: img=Image(url) insertdata(img,x,y,nowtime) except Exception,e: print e with open('./log/getynpic.log','a') as logfile: logfile.write('{0},{1}'.format(x,y)) logfile.write('\n')
def images_to_csv_with_label(csv_file, images, label, width, height): csv_file.write("label," + ",".join( ["pixel" + str(i) for i in range(0, int(width) * int(height))]) + "\n") for i, nameFile in enumerate(images): print(nameFile) csv_file.write(label + "," + ",".join( str(x) for x in misc.img_to_1d_gray( Image(nameFile).resize(width, height))) + "\n")
def detectBlobs(image_file): original = Image(image_file) blobs = original.findBlobs() for blob in blobs: blob.drawMinRect(color=Color.RED,width =10) #blobs[-1].drawMinRect(color=Color.RED,width =10) blobs.image = original #original.save("foundBlobs.jpg") return 1