class ThreadingObject(object): """ Threading object class The run() method will be started and it will run in the background until the application exits. """ def __init__(self, interval=1, video=False): """ Constructor :type interval: int :param interval: Check interval, in seconds """ self.interval = interval self.url = "http://192.168.10.222:1201/videostream.cgi?user=admin&pwd=" self.ipCam = JpegStreamCamera(self.url) self.display = Display() thread = threading.Thread(target=self.run, args=(video,)) thread.daemon = True # Daemonize thread thread.start() # Start the execution def run(self, video): """ Method that runs forever """ while not self.display.isDone(): if video: imagen = self.ipCam.live() else: imagen = self.ipCam.getImage().show() time.sleep(self.interval) imagen.quit()
def opticalFlow(): cam = Camera() img = cam.getImage().scale(.20) disp = Display(img.size()) img.save(disp) X = range(100) Y = [0 for i in range(100)] flag = 0 count = 0 while not disp.isDone(): ax.clear() count += 1 if flag == 0: imgA = cam.getImage().scale(0.20) flag += 1 else: imgB = cam.getImage().scale(0.20) imgB.save(disp) motion = imgB.findMotion(imgA) s = sum([i.magnitude() for i in motion]) imgA = imgB if count < 100: Y[count] = s else: Y.append(s) Y = Y[1:] X.append(count) X = X[1:] ax.bar(X, Y) plt.xlim(X[0], X[-1]) plt.draw()
def simpleDiff(): cam = Camera() img = cam.getImage().scale(.20) disp = Display(img.size()) img.save(disp) X = range(100) Y = [0 for i in range(100)] count = 0 imgA = cam.getImage().scale(0.20).grayscale() while not disp.isDone(): ax.clear() count += 1 time.sleep(0.1) imgB = cam.getImage().scale(0.20).grayscale() #imgB.save(disp) motion = (imgB - imgA).binarize().invert().erode(1).dilate(1) motion.save(disp) s = diff(motion) imgA = imgB if count < 100: Y[count] = s else: Y.append(s) Y = Y[1:] X.append(count) X = X[1:] ax.bar(X, Y) plt.xlim(X[0], X[-1]) plt.draw() imgA = imgB
def show_video(): dis = Display() try: while not dis.isDone(): capture_image().save(dis) sleep(1 / 25.0) except pygame.error: return
def calibrate(): winsize = (640, 480) display = Display(winsize) bg_img = get_image() bg_img.save(display) while not display.isDone(): img = get_image() img.save(display) if display.mouseLeft: return img.getPixel(display.mouseX, display.mouseY), bg_img, img
def getImage(video): url = "http://192.168.10.222:1201/videostream.cgi?user=admin&pwd=" ipCam = JpegStreamCamera(url) display = Display() if video==False: imagen = ipCam.getImage().show() while not display.isDone(): pass else: while not display.isDone(): imagen = ipCam.getImage() #faces = imagen.findHaarFeatures('face') #if faces is not None: # faces = faces.sortArea() # bigFace = faces[-1] # Draw a green box around the face # bigFace.draw() #imagen = ipCam.live() imagen.save(display) imagen.quit()
def ajusteFoto(filename,brillo=50,resolucion=(1024,768),modoExposicion='auto'): """ Va tomando fotos en un proceso de ensayo y error supervisado por el usuario , hasta que se toma la adecuada y el metodo devuelve el objeto imagen """ disp = Display(resolucion) try: while not disp.isDone(): img = tomaFoto(filename,brillo,resolucion,modoExposicion,altaVelocidad=False) img.save(disp) except: pass return img
p = self.articulaciones.pop() img.dl().line(puntoInicial, p, Color.BLUE, width=5) img.dl().circle(p, 10, Color.BLUE, width=5) img.applyLayers() self.angulosHuesos.append(aux.anguloLineaEntreDosPuntos(p, puntoInicial)) puntoInicial = p def depuracion(self): self.enDepuracion = True print " ---------------------" print "Areas: " print self.AreaBlobs print "Numero de blobs candidatos por area: " print self.numBlobsCandidatosPorArea print "Tiempo de tratamiento de imagen: " print self.tiempoTratamiento print "Numero Articulaciones detectadas: " print len(self.articulaciones) print " ---------------------" time.sleep(1) if __name__ == '__main__': display = Display() imgT = ImagenTratada() while not display.isDone(): img = imgT.capturaYTrataLaImagen(150) img.save(display)
from SimpleCV import Camera, Display from time import sleep myCamera = Camera(prop_set={'wdith': 320, 'height': 240}) myDisplay = Display(resolution=(320, 240)) while not myDisplay.isDone(): myCamera.getImage().save(myDisplay) sleep(.1)
def new_dewarp(self): vidpath = self.iVidPath #get input video path # isInROI is deprecated and not used in this program def isInROI(x, y, R1, R2, Cx, Cy): isInOuter = False isInInner = False xv = x - Cx yv = y - Cy rt = (xv * xv) + (yv * yv) if (rt < R2 * R2): isInOuter = True if (rt < R1 * R1): isInInner = True return isInOuter and not isInInner """ ws = width of input video hs = height of input video wd = width of destination/output video Hd = height of destinaton/output video """ def buildMap(Ws, Hs, Wd, Hd, R1, R2, Cx, Cy): #the function throws type error, if Wd and Hd are not converted to integers Hd = int(Hd) Wd = int(Wd) map_x = np.zeros((Hd, Wd), np.float32) map_y = np.zeros((Hd, Wd), np.float32) rMap = np.linspace(R1, R1 + (R2 - R1), Hd) thetaMap = np.linspace(0, 0 + float(Wd) * 2.0 * np.pi, Wd) sinMap = np.sin(thetaMap) cosMap = np.cos(thetaMap) for y in xrange(0, int(Hd - 1)): map_x[y] = Cx + rMap[y] * sinMap map_y[y] = Cy + rMap[y] * cosMap return map_x, map_y # do the unwarping def unwarp(img, xmap, ymap): output = cv2.remap(img.getNumpyCv2(), xmap, ymap, cv2.INTER_LINEAR) result = Image(output, cv2image=True) # return result return result disp = Display( (800, 600)) #initialise a 800x600 simplecv display to show preview #disp = Display((1296,972)) vals = [] last = (0, 0) # Load the video vc = VirtualCamera(vidpath, "video") # Sometimes there is crud at the begining, buffer it out for i in range(0, 10): img = vc.getImage() img.save(disp) # Show the user a frame let them left click the center # of the "donut" and the right inner and outer edge # in that order. Press esc to exit the display while not disp.isDone(): test = disp.leftButtonDownPosition() if test != last and test is not None: last = test print "[360fy]------- center = {0}\n".format(last) vals.append(test) print "[360fy]------- Dewarping video and generating frames using center, offset1, offset2\n" Cx = vals[0][0] Cy = vals[0][1] #print str(Cx) + " " + str(Cy) # Inner donut radius R1x = vals[1][0] R1y = vals[1][1] R1 = R1x - Cx #print str(R1) # outer donut radius R2x = vals[2][0] R2y = vals[2][1] R2 = R2x - Cx #print str(R2) # our input and output image siZes Wd = round(float(max(R1, R2)) * 2.0 * np.pi) #Wd = 2.0*((R2+R1)/2)*np.pi #Hd = (2.0*((R2+R1)/2)*np.pi) * (90/360) Hd = (R2 - R1) Ws = img.width Hs = img.height # build the pixel map, this could be sped up print "BUILDING MAP" xmap, ymap = buildMap(Ws, Hs, Wd, Hd, R1, R2, Cx, Cy) print "MAP DONE" result = unwarp(img, xmap, ymap) result.save(disp) print "[360fy]------- Storing frames into ../temp_data/frames\n" i = 0 while img is not None: print bcolors.OKBLUE + "\rFrame Number: {0}".format( i) + bcolors.ENDC, sys.stdout.flush( ) #flushes stdout so that frame numbers print continually without skipping #print " percent complete \r", result = unwarp(img, xmap, ymap) result.save(disp) # Save to file fname = "../temp_data/frames/FY{num:06d}.png".format(num=i) result.save(fname) img = vc.getImage() i = i + 1 print " \n" if img is None: self.statusText.setText(str("Status: Done")) disp.quit()
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)
cam = Camera() # Initialize the display display = Display() # Take an initial picture img = cam.getImage() # Write a message on the image img.drawText("Left click to save a photo.", 50, 50, color=Color().getRandom()) # Show the image on the display img.save(display) time.sleep(3) counter = 0 while not display.isDone(): # for window handling ## Pseudo live view img = cam.getImage() # get image # Update the display with the latest image img.save(display) # Since it's in while, It'll keep on rolling # and displaying making it appear # as live view. #################### if display.mouseLeft: # Save image to the current directory img.save("photobooth" + str(counter) + ".jpg") img.drawText("Photo saved.", 50, 50, color=Color().getRandom()) img.save(display)
from SimpleCV import Camera, Color, Display, Image cam = Camera() original_background = Image('weather.png') disp = Display() while not disp.isDone(): img = cam.getImage() img = img.flipHorizontal() bgcolor = img.getPixel(10, 10) dist = img.colorDistance(bgcolor) mask = dist.binarize(50) foreground = img - mask background = original_background - mask.invert() combined = background + foreground combined.save(disp)
from SimpleCV import Image, Display from time import sleep Display1 = Display() Image1 = Image("raspberrypi.png") Image1.save(Display1) while not Display1.isDone(): sleep(1)
from SimpleCV import Image, Color, Display from time import sleep import sys display = Display() # Load an image from imgur. img = Image('http://i.imgur.com/lfAeZ4n.png') # binarize the image using a threshold of 90 # and invert the results. output = img.binarize(90).invert() # create the side by side image. result = output result.save('juniperbinary.png') # show the resulting image. result.save(display) try: while not display.isDone(): sleep(0.1) except KeyboardInterrupt: sys.exit() # save the results to a file.
# -*- coding: utf-8 -*- from SimpleCV import Display, Image, Camera cam = Camera() display = Display() while display.isDone() == False: img = cam.getImage() img.show() exit()
class FingerTrackerPeaks(FingerTracker): """Finger tracking using peak-findings """ def __init__(self, camera=None): """Initialize the finger tracker :param TrackerIn ti: Tracker input :param camera: Camera index, filename, or None """ FingerTracker.__init__(self, camera) self.display = None def crop_img(self, img): return img.crop(50, 150, img.width - 100, img.height - 150) return img.crop(490, 95, img.width - 1000, img.height - 290).rotate(90, fixed=False) def find_fingers3(self, img, prev_img): if img is None or prev_img is None: return [] crop_spec = [0, 0, img.width, img.height] scale_factor = 2 r1 = img.grayscale().crop(*crop_spec) r2 = prev_img.grayscale().crop(*crop_spec) # modified diff = (r2 - r1).binarize(40) edge_mask = diff.erode(5).dilate(5) - diff.erode(5) edge_mask = edge_mask.dilate(5) scaled = (diff.edges() & edge_mask).resize(r1.width / scale_factor) points = [] for x in range(scaled.width): points.append(scaled.edgeIntersections((x, 0), (x, scaled.height))[0]) points = [xy for xy in points if xy is not None] if not points: return [] xs = range(scaled.width) ys = scipy.interp(range(scaled.width), [a[0] for a in points], [a[1] for a in points]) peaks = scipy.signal.find_peaks_cwt(-ys, np.arange(7, 11)) if len(peaks) == 0: return [] positions = np.array(zip(peaks, np.array(ys)[peaks])) * scale_factor + np.array(crop_spec[:2]) return positions def run_frame(self, ti, img): """Run the algorithm for one frame :param TrackerIn ti: TrackerIn object to send events to :return: True if I should be called with the next frame """ img = self.crop_img(img) if self.display is None: # Consume one frame for the initialization self.display = Display(img.size()) self.prev_img = img self.bg_img = None self.count = 20 self.last_time = time.time() return True elif self.display.isDone(): return False if self.bg_img is None and img: self.bg_img = img positions = self.find_fingers3(img, self.bg_img) if self.count > 0: self.bg_img = img self.count -= 1 print "SETTING BG IMAGE" di = img # (bg_img.grayscale() - img.grayscale()).binarize(40) for x, y in positions: di.dl().circle((int(x), int(y)), 15, color=Color.RED, width=3) self.add_positions(ti, positions) fps = 1.0 / (time.time() - self.last_time) di.dl().ezViewText("{0:.3f} fps".format(fps), (0, 0)) di.save(self.display) self.last_time = time.time() self.last_img = True if self.display.mouseLeft or self.display.mouseRight: self.display.done = True return False else: return True def finish(self): if self.display is not None: self.display.done = True self.display.quit()
from SimpleCV import Camera, Display, VideoStream, VirtualCamera, Color from time import sleep import numpy cam = Camera(prop_set={'width':320, 'height':240}) dis = Display(resolution=(320,240)) lastCoordinates = (0,0) vidStream = VideoStream("test.mov", 25, True) while not dis.isDone(): frame = cam.getImage() faces = frame.findHaarFeatures('face') if faces: for face in faces: # Checks to see if the (x,y) is greater than or less than the last (x,y). Then we have motion. if face.coordinates()[0] > lastCoordinates[0]+3 or face.coordinates()[1] > lastCoordinates[1]+3 or face.coordinates()[0] < lastCoordinates[0]-3 or face.coordinates()[1] < lastCoordinates[1]-3: lastCoordinates = face.coordinates() face.draw() frame.save(vidStream) # Show the image frame.show() # My attempt to get around 30 frames per second.. though I haven't checked this. sleep(1./30.) if dis.IsDone(): cam.close() dis.close()
squareConrnerY = centerPointY - boxHeight / 2 pic.drawRectangle(squareConrnerX, squareConrnerY, boxWidth, boxHeight) return windowSize = (640,480) # Initialize the webcam by providing URL to the camera cam = JpegStreamCamera("http://192.168.2.103:8080/video?submenu=mjpg") face = 0 display = Display(windowSize) img = cam.getImage() img.save(display) done = False while not done: if not display.isDone(): img = cam.getImage() test = {} # Dictionary containing difference images of a particular sticker and standard colors pixValues = [] # List containing the pixel values from (20,50) to (20,80) of each image present in test averagesDict = {} # Dictionary containing the average of pixValues corresponding to each color averagesList = [] # List containing all the average of pixValues corresponding to each color stickerColors = [[],[],[]] # Contains first letter of color of all the stickers in a picture DrawSquare(img, (320,240), 300) # Coordinates corresponding to the 'origin' of the cube squareCornerX = 170 squareCornerY = 90 for i in range(0,3): for j in range(0,3): croppedImg = img.crop(squareCornerX + j*100, squareCornerY + i*100, 100, 100) #to obtain just the sticker for color in rubikColor: test[color] = croppedImg.colorDistance(rubikColor[color])
from SimpleCV import Display, Image, Color winsize = (1300,750) display = Display(winsize) img = Image(winsize) #No image default black background of size same as display img.save(display) # Putting on display while not display.isDone(): # Display will b on till you close it if display.mouseLeft: # When left mouse button is pressed # Draw circles # dl() means accessing drawing layer and all the drawing function like the "Circle()" img.dl().circle((display.mouseX, display.mouseY), 4, Color.GREEN, filled=True) #update the window img.save(display) #Save as image as you close the window img.save("painting.png")
#!/usr/bin/env python # author: Powen Ko from SimpleCV import Image, Display from time import sleep import urllib url="https://chart.googleapis.com/chart?chs=150x150&cht=qr&chl=Hello%20world&choe=UTF-8" filename="out.jpg" urllib.urlretrieve(url,filename) Display1 = Display() img = Image(filename) img.save(Display1) # 顯示在畫面上 while not Display1.isDone(): sleep(1)