def detectCenter(image_file): original = Image(image_file) center_only = original.colorDistance((155,9,49))*8 mask = center_only.invert() #mask.save("center_mask.jpg") binarizedMask = mask.binarize().invert() #binarizedMask.save("binarized_mask_center.jpg") blobs = original.findBlobsFromMask(binarizedMask) if blobs == None : #print "No red found" return detectGreenLowQuality(image_file) bestBlob = blobs[-1] bestBlob.drawMinRect(color=Color.RED,width =10) bestBlob.image = original original.save("align.png") centroidX = bestBlob.minRectX() centroidY = bestBlob.minRectY() #Have to find out which part of the screen centroid is in maxX = original.getNumpy().shape[0] maxY = original.getNumpy().shape[1]+100 #assume width of 150 pixels return align_center(maxX,maxY,centroidX,centroidY,80,80)
def detectYellowLowQuality(image_file): original = Image(image_file) yellow_only = original.colorDistance((156,130,76))*2 #yellow_only = yellow_only*4 mask = yellow_only.invert() #mask.save("yellow_mask.jpg") binarizedMask = mask.binarize().invert() #binarizedMask.save("binarized_mask_yellow.jpg") blobs = original.findBlobsFromMask(binarizedMask) if blobs == None: #print "No yellow found" return -1 blobs[-1].drawMinRect(color=Color.RED,width =10) blobs.image = original #original.save("foundBlobs_yellow.jpg") bestBlob = blobs[-1] centroidX = bestBlob.minRectX() centroidY = bestBlob.minRectY() #Have to find out which part of the screen centroid is in maxX = original.getNumpy().shape[0] maxY = original.getNumpy().shape[1]+100 #assume width of 150 pixels return align_center(maxX,maxY,centroidX,centroidY,50,50)
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)
def detectGreenLowQuality(image_file): original = Image(image_file) #binarizedYellowMask = findYellowMask(image_file) #subtractedMask = original - binarizedYellowMask #subtractedMask.save("subtractedMask.jpg") #green_only = subtractedMask.colorDistance((94,116,33)) #green_only = subtractedMask.colorDistance((50,116,45)) green_only = original.colorDistance((0,70,6)) green_only = green_only*6 mask = green_only.invert() #mask.save("green_mask.jpg") binarizedMask = mask.binarize().invert() #binarizedMask.save("binarized_mask_green.jpg") blobs = original.findBlobsFromMask(binarizedMask) if blobs == None: #print "No green found" return detectYellowLowQuality(image_file) blobs.image = original #Assume best blob is the largest blob bestBlob = blobs[-1] bestBlob.drawMinRect(color=Color.RED,width =10) #original.save("foundBlobs_green.jpg") ''' #blobs[-1].drawRect(color=Color.RED,width =10) coordinates = bestBlob.minRect() #Find the center point centroidX = bestBlob.minRectX() centroidY = bestBlob.minRectY() minLeftY = 0 minRightY = 0 #Find the bottom left and bottom right coordinates for coordinate in coordinates: if coordinate[0] < centroidX and coordinate[1] > minLeftY: bottomLeft = coordinate minLeftY = coordinate[1] elif coordinate[0] > centroidX and coordinate[1] > minRightY: bottomRight = coordinate minRightY = coordinate[1] ''' centroidX = bestBlob.minRectX() centroidY = bestBlob.minRectY() #Have to find out which part of the screen centroid is in maxX = original.getNumpy().shape[0] maxY = original.getNumpy().shape[1]+100 #assume width of 150 pixels return align_center(maxX,maxY,centroidX,centroidY,50,50)
#!/usr/bin/env python #!encoding=utf8 from SimpleCV import Image from sklearn.feature_extraction.image import img_to_graph img = Image('./digits.bmp') img_np = img.getNumpy() graph = img_to_graph(img_np) print graph
from SimpleCV import Image from NdArrayIndexer import NdArrayIndexer print '========================================================================' print 'RGB Image' print '========================================================================' print print 'Converting RGB image to ndarray' img = Image("img/rgb2x3.png") rgb_img = img.getNumpy() print print 'Original ndarray after conversion from RGB image:' print rgb_img print print 'rgb_img is array([[[r1, g1, b1], [rn, gn, bn]], [...]])' print 'Where r is Red, g is Green and b is Blue dimensions by pixel.' print 'The axe 0 is the coordinate y and the axe 1 is the coordinate x.' print 'Now we are going to get the coordinates per pixel.' print
from SimpleCV import Image import numpy as np diff = Image("lena.jpg") matrix = diff.getNumpy() flat = matrix.flatten() num_change = np.count_nonzero(flat) percent_change = float(num_change) / float(len(flat)) if percent_change > 0.1: print "miss match"
from SimpleCV import Image x = Image("image_blue.png") y = x.getNumpy() print y[341][208];
from SimpleCV import Image import numpy img = Image("us-scaled.jpg") out = img.binarize(30) out.save('out.png') img = Image("out.png") # ones = img.getNumpy()[:,:,:] == (0, 0, 0) ones = img.getNumpy()[:,:,0] == 0 trues=numpy.where(ones) points = [] for p in zip(trues[0], trues[1]): # points.append(p) print(str(p[0]) + " " + str(p[1])) for one in ones: print(one)
def run(self): server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((CONFIG_LISTEN_HOST, CONFIG_LISTEN_PORT)) server_socket.listen(1) # max 1 connection - we only have one camera, so we can't send images to two people at once print('Listening on port %s' % CONFIG_LISTEN_PORT) connection = None while True: connection, address = server_socket.accept() try: # Don't let any bad things that happen with one connection cause the whole server to crash data = connection.recv(1024) print('Got some data:') print(data) print("Data over.") if data == 'GETIMG': # They want a raw image try: if camera_connected(): # give them the current camera image img = c.getImage() else: # Looks like the camera disconnected randomly img = Image("res/img/connect_failed.png") except AttributeError: # Occurs when the camera was never connected in the first place img = Image("res/img/connect_failed.png") # Encode as JPEG so we don't have to send so much encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90] result, encoded_img = cv2.imencode('.jpg', img.getNumpy(), encode_param) img_numpy = numpy.array(encoded_img) img_str = img_numpy.tostring() # Send the size of the image, so that the client can handle if we have to send it in multiple parts connection.send(str(len(img_str)).ljust(16)) # Send the image itself connection.send(img_str) elif data == "NEWCONFIG": # They're sending us a new config to use connection.send('READY') newconf_data = connection.recv(1024) newconf = json.loads(newconf_data) # Set values to the new ones we just got conf.min_lum = newconf.get('min_lum') conf.max_lum = newconf.get('max_lum') conf.min_sat = newconf.get('min_sat') conf.max_sat = newconf.get('max_sat') conf.min_hue = newconf.get('min_hue') conf.max_hue = newconf.get('max_hue') connection.send('SUCCESS') # We successfully processed the new config print('Got a new config') conf.save("conf/values.json") # Save our new config elif data == "GETCONFIG": class ConfigEncoder(json.JSONEncoder): def default(self, o): return o.__dict__ connection.send(ConfigEncoder().encode(conf)) # Send a json representation of our config elif data == "GETCAMPROPS": proc = subprocess.Popen(['v4l2-ctl', '--list-ctrls', '--device=/dev/video%s' % cam_id], stdout=subprocess.PIPE) out, err = proc.communicate() connection.send(str(len(out)).ljust(16)) connection.send(out) elif data == "STARTV4LPROPS": while True: length = int(connection.recv(16)) dta = connection.recv(length) if dta is None or dta == "ENDV4LPROPS" or not dta.startswith('UPDATEV4L'): break else: words = dta.split(' ') val_name = words[1].strip() val_value = int(words[2].strip()) print(val_name) print(val_value) proc = subprocess.Popen(['v4l2-ctl', "--device=/dev/video%s" % cam_id, '-c', "%s=%s" % (val_name, val_value)], stdout=subprocess.PIPE) # TODO see if the command is good proc.communicate() except Exception as ex: print(ex.message) connection.close() connection.close()