def face_recognize(filename): from SimpleCV import Image, Display, DrawingLayer image = Image(filename) faces = image.findHaarFeatures('face.xml') if faces: for face in faces: face_layer = DrawingLayer((image.width, image.height)) face_box = face_layer.centeredRectangle(face.coordinates(), (face.width(), face.height())) image.addDrawingLayer(face_layer) image.applyLayers() image.save(filename) print('偵測到 {} 張人臉'.format(len(faces))) else: print('沒有偵測到人臉')
def face_recognize(filename): from SimpleCV import Image, Display, DrawingLayer image = Image(filename) faces = image.findHaarFeatures('face.xml') if faces: for face in faces: face_layer = DrawingLayer((image.width, image.height)) face_box = face_layer.centeredRectangle( face.coordinates(), (face.width(), face.height())) image.addDrawingLayer(face_layer) image.applyLayers() image.save(filename) print('偵測到 {} 張人臉'.format(len(faces))) else: print('沒有偵測到人臉')
def drawImage(): #Load Map d = Display((1240, 820), title="London Map - Scotland Yard") lMap = Image("maps/map.jpg") #Check Position from players #See corresponding pixel in list #Draw Circle from players circlesLayer = DrawingLayer((lMap.width, lMap.height)) circlesLayer.circle ((191,44), 20,color=Color.BLACK, filled=True, alpha = 255) lMap.addDrawingLayer(circlesLayer) #Display lMap.applyLayers() lMap.save(d) '''Later create a "draw possibilites" areas in map for thief '''
def _removeAllButCentralGalaxyCluster(self): e = self.ellipse img = self.image emask = Image(np.zeros((img.width, img.height), dtype=np.uint8)) if e and e.a and e.b and e.a != np.nan and e.b != np.nan: try: e.drawOntoLayer(emask) except: print "Got exception while processing %s" % self.id pass emask = emask.applyLayers().floodFill((img.width/2, img.height/2), color=Color.BLUE) mask = emask.binarize().invert() return img.applyBinaryMask(mask)
def constructMask(w, h, offset, expf=1.2): # Create an alpha blur on the left followed by white # using some exponential value to get better results mask = Image((w, h)) offset = int(offset) for i in range(0, offset): factor = np.clip((float(i)**expf) / float(offset), 0.0, 1.0) c = int(factor * 255.0) #this is oddness in slice, need to submit bug report mask[i:i + 1, 0:h] = (c, c, c) mask.drawRectangle(offset, 0, w - offset, h, color=(255, 255, 255), width=-1) mask = mask.applyLayers() return mask
def __call__(self, image): params = util.utf8convert(self.inspection.parameters) retVal = [] mask = Image((image.width,image.height)) if( params.has_key('w') and params.has_key('h') and params.has_key('x') and params.has_key('y') ): #rectangle if( params['x'] + params['w'] < image.width and params['y'] + params['h'] < image.height and params['y'] >= 0 and params['x'] >= 0 ): mask.drawRectangle(params['x'],params['y'],params['w'],params['h'],width=-1,color=Color.WHITE) mask = mask.applyLayers() fs = image.findBlobsFromMask(mask) ff = M.FrameFeature() if( fs is not None and len(fs) > 0 ): #fs[-1].draw() b = fs[-1] b.__class__ = BlobRegion c = b.meanColor() b.mColor = (int(c[0]),int(c[1]),int(c[2])) ff.setFeature(b) # a little hacky but I am sure that it works retVal = [ff] elif( params.has_key('x') and params.has_key('y') and params.has_key('r') ): # circle if( params['x'] + params['r'] < image.width and params['y'] + params['r'] < image.height and params['x'] - params['r'] >= 0 and params['y'] - params['r'] >= 0 ): r = params['r'] x = params['x'] y = params['y'] mask.drawCircle((x,y),r,thickness=-1,color=Color.WHITE) mask = mask.applyLayers() fs = image.findBlobsFromMask(mask) ff = M.FrameFeature() if( fs is not None and len(fs) > 0 ): #fs[-1].draw() b = fs[-1] b.__class__ = BlobRegion c = b.meanColor() b.mColor = (int(c[0]),int(c[1]),int(c[2])) ff.setFeature(b) retVal = [ff] elif( params.has_key('contour') ): contour = params['contour'] # this may bail out if( len(contour) >= 3 ): mask.dl().polygon(contour,filled=True,color=Color.WHITE) mask = mask.applyLayers() fs = image.findBlobsFromMask(mask) ff = M.FrameFeature() if( fs is not None and len(fs) > 0 ): #fs[-1].draw() b = fs[-1] b.__class__ = BlobRegion c = b.meanColor() b.mColor = (int(c[0]),int(c[1]),int(c[2])) ff.setFeature(b) retVal = [ff] if( params.has_key("saveFile") ): image.save(params["saveFile"]) return retVal
from SimpleCV import Image, Color, Display # load an image from imgur img = Image('http://i.imgur.com/lfAeZ4n.png') # use a keypoint detector to find areas of interest feats = img.findKeypoints() # draw the list of keypoints feats.draw(color=Color.RED) # show the resulting image. img.show() # apply the stuff we found to the image. output = img.applyLayers() # save the results. output.save('juniperfeats.png')
img = Image('stenramchiffontest.jpg') disp = Display() img_blurred = img.gaussianBlur((101, 101)) # Make a mask mask_size = 80 mask = Image((4 * mask_size, 4 * mask_size)) dl = DrawingLayer((4 * mask_size, 4 * mask_size)) # Draw a filled circle in the mask dl.circle((2 * mask_size, 2 * mask_size), mask_size, filled=True, color=Color.WHITE) mask.addDrawingLayer(dl) mask = mask.applyLayers() blurred_mask = mask.gaussianBlur((101, 101)) t0 = time.time() # Blur the mask to get progressive blur n = 3 img_ = img.gaussianBlur((n, n)) old_n = 3 isDown = False mouseRawXOld = 0 x = 0 while not disp.isDone(): t = time.time() dt = t - t0 t0 = t mouseRawX = disp.mouseRawX
from SimpleCV import Image, DrawingLayer, Color, Display d = Display((1240, 820), title="London Map - Scotland Yard") lMap = Image("C:\\Users\\flavio\\Documents\\Python\\Scotland Yard\\maps\\map.jpg") circlesLayer = DrawingLayer((lMap.width, lMap.height)) circlesLayer.circle ((191,44), 20,color=Color.ORANGE, filled=True, alpha = 255) lMap.addDrawingLayer(circlesLayer) lMap.applyLayers() lMap.save(d)
def fancify(): if request.method == 'POST': print request.data cur_request = json.loads(request.data) else: #cur_request = """{"url": "", "debug":true}""" #cur_request = """{"url": "", "debug":true}""" #cur_request = """{"url": "", "debug":true}""" cur_request = """{"url": "http://localhost/images/scrubs.jpg", "debug":true}""" #cur_request = """{"url": "http://www.newrichstrategies.com/wp-content/uploads/2012/03/How-to-Find-Good-People-in-Your-Life.jpg", "debug":false}""" #cur_request = """{"url": "http://greenobles.com/data_images/frank-lampard/frank-lampard-02.jpg", "debug":true}""" #cur_request = """{"url": "http://www.billslater.com/barack__obama.jpg"}""" #cur_request = """{"url": "http://celebrityroast.com/wp-content/uploads/2011/01/arnold-schwarzenegger-body-building.jpg", "debug":false}""" #cur_request = """{"url": "http://face2face.si.edu/.a/6a00e550199efb8833010536a5483e970c-800wi", "debug":true}""" #cur_request = """{"url": "http://collider.com/uploads/imageGallery/Scrubs/scrubs_cast_image__medium_.jpg", "debug":false}""" #cur_request = """{"url": "http://localhost/images/Kevin_Bacon_at_the_2010_SAG_Awards.jpg", "debug":false}""" #cur_request = """{"url": "http://cdn02.cdn.justjared.com/wp-content/uploads/headlines/2012/02/anna-faris-oscars-red-carpet-2012.jpg", "debug":true}""" #cur_request = """{"url": "http://www.viewzone.com/attractive.female.jpg", "debug":true}""" cur_request = json.loads(cur_request) print cur_request["url"] img = Image(str(cur_request["url"])) img = img.scale(2.0) debug = True #if "debug" in cur_request: # debug = cur_request["debug"] chosen_faces = [] faces = img.findHaarFeatures(face_cascade) if faces is not None: for face in faces: face_features = [] invalid_face = False face_rect = Rect(face.x - (face.width() / 2), face.y - (face.height() / 2), face.width(), face.height()) for chosen_face in chosen_faces: if face_rect.colliderect(chosen_face): invalid_face = True break if invalid_face: break nose = None mouth = None left_eye = None right_eye = None cur_face = img.crop(face.x, face.y, face.width(), face.height(), centered=True) #cur_face = face.crop() noses = cur_face.findHaarFeatures(nose_cascade) mouths = cur_face.findHaarFeatures(mouth_cascade) eyes = cur_face.findHaarFeatures(eye_cascade) face_left_edge = face.x - (face.width() / 2) face_top_edge = face.y - (face.height() / 2) if noses is not None: nose = noses[0] nose_dist = (abs(nose.x - (face.width() / 2)) + abs(nose.y - (face.height() * 5 / 9)) + abs(nose.width() - (face.width() / 4))) for cur_nose in noses: cur_dist = (abs(cur_nose.x - (face.width() / 2)) + abs(cur_nose.y - (face.height() * 5 / 9)) + abs(cur_nose.width() - (face.width() / 4))) if cur_dist < nose_dist: nose = cur_nose nost_dist = cur_dist if nose and (nose.y < (face.height() / 3)): nose = None if nose and mouths is not None: mouth = mouths[0] mouth_dist = abs(mouth.x - nose.x) + (abs(mouth.y - (face.height() * 4 / 5)) * 2) for cur_mouth in mouths: cur_dist = abs(cur_mouth.x - nose.x) + (abs(cur_mouth.y - (face.height() * 4/ 5)) * 2) if (cur_dist < mouth_dist) and (cur_mouth.y > nose.y): mouth = cur_mouth mouth_dist = cur_dist if nose and eyes: right_eye = eyes[0] right_eye_dist = (abs(right_eye.x - (3 * face.width() / 4)) * 2 + abs(right_eye.y - (nose.y - (nose.height() / 2)) / 2) + abs(right_eye.width() - (face.width() / 3))) for cur_eye in eyes: cur_right_dist = (abs(cur_eye.x - (3 * face.width() / 4)) + abs(cur_eye.y - (nose.y - (nose.height() / 2)) / 2) + abs(cur_eye.width() - (face.width() / 3))) if (cur_right_dist <= right_eye_dist): # and (cur_eye.y < nose.y): right_eye = cur_eye right_eye_dist = cur_right_dist if nose and right_eye and (((right_eye.y - (right_eye.height() / 2)) > nose.y) or (right_eye.x < nose.x)): print "Culling right_eye" right_eye = None if nose and mouth: chosen_faces.append(face_rect) x_face = face.x - (face.width() / 2) y_face = face.y - (face.height() / 2) x_nose = nose.x - (nose.width() / 2) y_nose = nose.y - (nose.height() / 2) # Setup TopHat Image scale_factor = face.width() / 175.0 cur_hat = hat.copy() cur_hat = cur_hat.scale(scale_factor) cur_hat_mask = hat_mask.copy() cur_hat_mask = cur_hat_mask.scale(scale_factor) cur_hat_mask = cur_hat_mask.createAlphaMask(hue_lb=0, hue_ub=100) # Calculate the hat position if (face.y - face.height() / 2) > cur_hat.height: x_hat = face.x - (cur_hat.width / 2) y_hat = face.y - (face.height() * 7 / 10) - (cur_hat.height / 2) img = img.blit(cur_hat, pos=(x_hat, y_hat), alphaMask=cur_hat_mask) if mouth: x_mouth = mouth.x - (mouth.width() / 2) y_mouth = mouth.y - (mouth.height() / 2) # Setup Mustache Image cur_stache = stache.copy() scale_factor = ((nose.width() / 300.0) + (face.width() / 600.0)) / 2.0 cur_stache = cur_stache.scale(scale_factor) stache_mask = cur_stache.createAlphaMask(hue_lb=0, hue_ub=10).invert() # Calculate the mustache position bottom_of_nose = y_nose + (nose.height() * 4 / 5) top_of_mouth = y_mouth # if top_of_mouth > bottom_of_nose: # top_of_mouth = bottom_of_nose y_must = y_face + ((bottom_of_nose + top_of_mouth) / 2) - (cur_stache.height / 2) middle_of_nose = nose.x middle_of_mouth = mouth.x x_must = x_face + ((middle_of_nose + middle_of_mouth) / 2) - (cur_stache.width / 2) if right_eye: x_right_eye = right_eye.x - (right_eye.width() / 2) y_right_eye = right_eye.y - (right_eye.height() / 2) # Setup Monocle Image cur_mono = monocle.copy() scale_factor = ((right_eye.width() / 65.0) + (face.width() / 200.0)) / 2.0 cur_mono = cur_mono.scale(scale_factor) mono_mask = cur_mono.createAlphaMask(hue_lb=0, hue_ub=100).invert() # Calculate Monocle Position x_mono = x_face + x_right_eye y_mono = y_face + y_right_eye img = img.blit(cur_mono, pos=(x_mono, y_mono), alphaMask=mono_mask) img = img.blit(cur_stache, pos=(x_must, y_must), alphaMask=stache_mask) if debug: noselayer = DrawingLayer((img.width, img.height)) nosebox_dimensions = (nose.width(), nose.height()) center_point = (face.x - (face.width() / 2) + nose.x, face.y - (face.height() / 2) + nose.y) nosebox = noselayer.centeredRectangle(center_point, nosebox_dimensions, width=3) img.addDrawingLayer(noselayer) img = img.applyLayers() else: print "Face culled:" if not nose: print " No Nose" if not mouth: print " No mouth" if not right_eye: print " No right eye" print if debug: face_left_edge = face.x - (face.width() / 2) face_top_edge = face.y - (face.height() / 2) facelayer = DrawingLayer((img.width, img.height)) facebox_dimensions = (face.width(), face.height()) center_point = (face.x, face.y) facebox = facelayer.centeredRectangle(center_point, facebox_dimensions, Color.BLUE) img.addDrawingLayer(facelayer) if noses: for nose in noses: noselayer = DrawingLayer((img.width, img.height)) nosebox_dimensions = (nose.width(), nose.height()) center_point = (face.x - (face.width() / 2) + nose.x, face.y - (face.height() / 2) + nose.y) nosebox = noselayer.centeredRectangle(center_point, nosebox_dimensions) img.addDrawingLayer(noselayer) if mouths: for mouth in mouths: mouthlayer = DrawingLayer((img.width, img.height)) mouthbox_dimensions = (mouth.width(), mouth.height()) center_point = (face.x - (face.width() / 2) + mouth.x, face.y - (face.height() / 2) + mouth.y) mouthbox = mouthlayer.centeredRectangle(center_point, mouthbox_dimensions, Color.GREEN) img.addDrawingLayer(mouthlayer) if eyes: for right_eye in eyes: right_eyelayer = DrawingLayer((img.width, img.height)) right_eyebox_dimensions = (right_eye.width(), right_eye.height()) right_eye_center_point = (face_left_edge + right_eye.x, face_top_edge + right_eye.y) right_eyebox = right_eyelayer.centeredRectangle(right_eye_center_point, right_eyebox_dimensions) img.addDrawingLayer(right_eyelayer) img = img.applyLayers() img = img.scale(0.5) w_ratio = img.width / 800.0 h_ratio = img.height / 600.0 if h_ratio > 1.0 or w_ratio > 1.0: if h_ratio > w_ratio: img = img.resize(h=600) else: img = img.resize(w=800) output = StringIO.StringIO() img.getPIL().save(output, format="JPEG") #, quality=85, optimize=True) img_contents = output.getvalue() mimetype = "image/jpeg" return app.response_class(img_contents, mimetype=mimetype, direct_passthrough=False)
def findMA(path, file_name_without_extension): eye = Image(path) (empty, eye_green, emptier) = eye.splitChannels(False) eye_green = eye_green * 2.5 eye_gray = eye_green.grayscale() eye_gray = eye_gray.smooth() #Canny edge detection algorithm. t1 specifies the threshold value to begin an edge. t2 specifies the strength required #build an edge off of a point found by T2. eye_edges = eye_gray.edges(t1=70, t2=35) edge_test = eye_gray + eye_edges eye_final = eye_edges #Perform closing to find individual objects eye_final = eye_final.dilate(2) eye_final = eye_final.erode() eye_final = eye_final.dilate(4) eye_final = eye_final.erode(3) big_blobs = eye_final.findBlobs(minsize=500) #create a blank image to mask masked_image = Image(eye.size()) for b in big_blobs: #set mask b.image = masked_image #draw the blob on your mask b.draw(color=Color.WHITE) eye_final = eye_final - masked_image.applyLayers() eye_final = eye_final.erode() eye_final = eye_final.grayscale() print(eye_final[100, 200][0]) print(eye_final[200, 300]) print(eye_final[400, 600]) #eye_final.save("testthis.png") if eye_final.findBlobs(maxsize=10): small_blobs = eye_final.findBlobs(maxsize=10) #create a blank image to mask masked_small_image = Image(eye.size()) for b in small_blobs: #set mask b.image = masked_small_image #draw the blob on your mask b.draw(color=Color.WHITE) eye_final = eye_final - masked_small_image.applyLayers() # print("secondtime") print(eye_final[100, 200]) print(eye_final[200, 300]) print(eye_final[400, 600]) if eye_final.findBlobs(): final_blobs = eye_final.findBlobs() #Filter through objects to find only potential microaneurysms masked_circle_image = Image(eye.size()) for b in final_blobs: blob_height = b.height() blob_width = b.width() width_height_diff = abs(blob_height - blob_width) if (width_height_diff > .2 * blob_height) | (width_height_diff > .2 * blob_width): b.image = masked_circle_image b.draw(color=Color.WHITE) if (b.area() < .45 * blob_height * blob_width): b.image = masked_circle_image b.draw(color=Color.WHITE) #remove large pointless blobs if (b.area() > 1500): b.image = masked_circle_image b.draw(color=Color.WHITE) #Save different objects #eye_final.save("Output1.png") #masked_circle_image.applyLayers().save("Output2.png") eye_final = eye_final - masked_circle_image.applyLayers() eye_example = eye_final + eye # print("third time") print(eye_final[100, 200]) print(eye_final[200, 300]) print(eye_final[400, 600]) eye_example.save(file_name_without_extension + '_MAoverlay.tif') print("overlay saved") eye_final.save(file_name_without_extension + '_MA.tif') print("MA saved") # print("fourth time") print(eye_final[140, 140]) print(eye_final[180, 180]) print(eye_final[350, 350]) # print('lag gye') return eye_final
big_blobs = eye_final.findBlobs(minsize=500) #create a blank image to mask masked_image = Image(eye.size()) for b in big_blobs: #set mask b.image = masked_image #draw the blob on your mask b.draw(color = Color.WHITE) eye_final = eye_final - masked_image.applyLayers() eye_final = eye_final.erode() #eye_final.save("testthis.png") if eye_final.findBlobs(maxsize=10): small_blobs = eye_final.findBlobs(maxsize=10) #create a blank image to mask masked_small_image = Image(eye.size()) for b in small_blobs: #set mask b.image = masked_small_image
from SimpleCV import Color, Image import time img = Image("sportsballs.jpg") circles = img.findCircle(canny=200, thresh=250, distance=15) circles.sortArea() circles.draw(width=4) circles[0].draw(color=Color.RED, width=4) img_with_circles = img.applyLayers() edges_in_image = img.edges(t2=200) final = img.sideBySide(edges_in_image.sideBySide(img_with_circles)).scale(0.5) final.show() time.sleep(15)
invertidos=green.invert()#se invierte la imagen para obtener manchas negras en la foto blob=invertidos.findBlobs()#se ve si se encuentrasn las mannchas en la foto invertida blob.show(width=2) pruebalunar.addDrawingLayer(invertidos.dl()) pruebalunar.show() pruebalunar.save("porfavorguardate2.png") #guardamos la imagen #enncontrar manchas por color especifico para el cual tenemos: brown_distance=green.colorDistance(Color.BLACK).invert()##cmo buscamos de color negro , le pknemos black blobs2_=brown_distance.findBlobs() blobs2_.draw(color=Color.PUCE ,width=3)#se va hacer el mismo ejemplo de la guia brown_distance.show() green.addDrawingLayer(brown_distance.dl()) green.show() green.save("Porfavorguaradte5.png") #lineas=pruebalunar.findLines() #lineas.draw(width=3) #pruebalunar.show() circles=pruebalunar.findCircle(canny=100,thresh=350,distance=15) circles=circles.sortArea() circles.draw(width=4) img_with_circles= pruebalunar.applyLayers() edges_in_image= pruebalunar.edges(t2=200) final=pruebalunar.sideBySide(edges_in_image.sideBySide(img_with_circles)).scale(0.5) final.show() final.save("porfavorguardate.png")
def detectChargingStation(image_file): debug = False myColor1 = (8,33,64) myColor2 = (70,80,100) original = Image(image_file) only_station = onlyBlueColor(original, myColor1) #Different findBlobs maskMean = original.hueDistance(color=(200,160,150)) mask = only_station.hueDistance(color=myColor1).binarize() meanColor = (round(((maskMean.meanColor()[0]+maskMean.meanColor()[1]+maskMean.meanColor()[2])/3) * 10000)/10000) blobs = original.findBlobsFromMask(mask, minsize=400) if(meanColor > 190): return 6 #print "Number of blobs found" , len(blobs) try: blobs.image = original except Exception: only_station = onlyBlueColor(original, myColor2) mask = only_station.hueDistance(color=myColor2).binarize() blobs = original.findBlobsFromMask(mask, minsize=400) blobs.image = original station_blob = chooseBestBlobCosine(blobs) station_blob.drawMinRect(color=Color.RED) centroidX = station_blob.minRectX() centroidY = station_blob.minRectY() #Have to find out which part of the screen centroid is in maxX = original.getNumpy().shape[0] maxY = original.getNumpy().shape[1]+100 if(debug): centroidLayer = DrawingLayer((maxX,maxY)) centroidLayer.line((0,(1/3.0)*maxY),(maxX, (1/3.0)*maxY), color=Color.GREEN, width=2) centroidLayer.line((0,(2/3.0)*maxY),(maxX, (2/3.0)*maxY), color=Color.GREEN, width=2) centroidLayer.circle((int(centroidX), int(centroidY)), color=Color.GREEN, radius=5, filled=True) original.addDrawingLayer(centroidLayer) original.applyLayers() mask.save("binarizeMask.png") original.save("blobs.png") only_station.save("blueFilter.png") #print "Coordinates of centroid are "+str(centroidX)+", "+str(centroidY) #print "Coordinates of max are "+str(maxX)+", "+str(maxY) #if(station_blob.width() * station_blob.height() < 4000): # return 2 blobArea = station_blob.width() * station_blob.height() if(blobArea < 10000): return 2 return chargingStationLocation_New(maxX,maxY,centroidX,centroidY,200, station_blob.width() / float(station_blob.height()), blobArea)
from SimpleCV import Image,Display,DrawingLayer,Color from time import sleep myDisplay = Display() raspberryImage = Image("test.jpg") myDrawingLayer = DrawingLayer((raspberryImage.width, raspberryImage.height)) myDrawingLayer.rectangle((50,20),(250,60),filled=True) myDrawingLayer.setFontSize(45) myDrawingLayer.text("Raspberries!",(50,20),color=Color.WHITE) raspberryImage.addDrawingLayer(myDrawingLayer) raspberryImage.applyLayers() raspberryImage.save(myDisplay) while not myDisplay.isDone(): sleep(0.1)
if __name__ == '__main__': cam = Camera(0) img = Image() samples = 0 coordinates = redCoords = (0,0) text = " " while True: img = cam.getImage() # Make image black and white tmp = findRedDot(img) if (tmp != None): coordinates= (coordinates[0]+tmp[0][0], coordinates[1]+tmp[0][1]) samples+=1 if samples == 10: samples = 0 coordinates = (coordinates[0]/10, coordinates[1]/10) text = str(coordinates) redCoords = coordinates coordinates = (0,0) redcircle = DrawingLayer((img.width, img.height)) redcircle.circle(redCoords, 5, filled=True, color=(0,255,0)) #add circle point 10,10, radius 10. img.addDrawingLayer(redcircle) img.applyLayers() img.drawText(text) img.show()