def main(): """ get coordinates and distance of a single ball (closest) """ camera = Camera(1, 648.5256168410046, 0.340394) ball = ImageObject(0.22510163906500055 / 2) while True: ok, frame = camera.read() cv2.imshow('feed', pipeline(frame)) cnt = pipeline1(frame) if cnt is not None: cv2.drawContours(frame, [cnt], 0, (0, 255, 0), 2) c = pipeline3(cnt) cv2.circle(frame, c, 2, (0, 0, 255), 2) cv2.circle(frame, (frame.shape[1] // 2, frame.shape[0] // 2), 2, (255, 0, 0), 2) cv2.imshow('original', frame) k = cv2.waitKey(1) & 0xFF if k == ord('d'): print(ball.location2d(camera, pipeline1, frame)) print(ball.distance(camera, pipeline4, frame)) if k == ord('c'): cv2.destroyAllWindows() break
def get_labeled_ball_images(): """ get coordinates and distance of all balls """ camera = Camera(0, 648.5256168410046, 0.340394) ball = ImageObject(0.22510163906500055 / 2) images = [] while True: ok, frame = camera.read() cv2.imshow('feed', pipeline(frame)) cnts = list(pipeline_cnts(frame)) rs = [] centers = [] new_images = [] for i in images: i.was_found = False if len(cnts) > 0: for cnt in cnts: to_continue = False center, r = cv2.minEnclosingCircle(cnt) center = np.array(center, dtype=int) r = int(r) b_img = np.copy(frame[center[1] - r:center[1] + r, center[0] - r:center[0] + r, :]) for i in range(len(rs)): if is_circle_invalid(center1=center, r1=r, center2=centers[i], r2=rs[i]): to_continue = True break if to_continue: continue if not find_ball_in_list(center, r, images, b_img): new_images.append(ImageOfObject(b_img, center, r)) rs.append(r) centers.append(center) images.extend(new_images) for i, img in enumerate(images): if not img.was_found: img.save() del images[i] for ind, center in enumerate(centers): cv2.circle(frame, tuple(map(int, center)), int(rs[ind]), (0, 255, 0), 2) cv2.circle(frame, tuple(map(int, center)), 2, (0, 0, 255), 2) cv2.circle(frame, (frame.shape[1] // 2, frame.shape[0] // 2), 2, (255, 0, 0), 2) cv2.imshow('original', frame) k = cv2.waitKey(1) & 0xFF if k == ord('c'): cv2.destroyAllWindows() break
def main2(): """ get coordinates and distance of all balls """ camera = Camera(1, 648.5256168410046, 0.340394) ball = ImageObject(0.22510163906500055 / 2) while True: ok, frame = camera.read() cv2.imshow('feed', pipeline(frame)) cnts = list(pipeline_cnts(frame)) d = [] d_norm = [] if len(cnts) > 0: for cnt in cnts: c = pipeline3(cnt) cv2.drawContours(frame, [cnt], 0, (0, 255, 0), 2) cv2.circle(frame, c, 2, (0, 0, 255), 2) d.append(ball.location2d_by_contours(camera, cnt)) d_norm.append(ball.distance_by_contours(camera, cnt)) cv2.circle(frame, (frame.shape[1] // 2, frame.shape[0] // 2), 2, (255, 0, 0), 2) cv2.imshow('original', frame) k = cv2.waitKey(1) & 0xFF if k == ord('d'): print(d) print(d_norm) if k == ord('c'): cv2.destroyAllWindows() break
def main(args): confs = CameraConfig(args.config_file) ncams = confs.n_cameras() cams = CameraList() archive = Archive(confs) framenos = [0] * ncams location = confs.data['location'] sleep = confs.data['cameras'][0]['sleep'] start_video = confs.data['cameras'][0]['start_video'] stop_video = confs.data['cameras'][0]['stop_video'] for c in confs.data['cameras']: camid = c['id'] addr = c['url'] cam = Camera(addr, camid) cams.append(cam) framenos[cam.camid] = int(archive.next_prefix(cam.camid)) while True: if is_daylight(location) or args.debug: for i, cam in enumerate(cams): im = cam.grab() timestamp = datetime.now() if im is None: break framenos[i] += 1 archive.save_image(cam.camid, timestamp, framenos[i], im) time.sleep(sleep)
def __init__(self, image_dest, fullscreen, debug, webcam, print_count, printer, upload_to): self.debug = debug if debug: self.camera = DebugCamera() elif webcam: self.camera = WebcamCamera() else: self.camera = Camera() if self.debug: self.count_down_time = 2 self.image_display_time = 3 self.montage_display_time = 8 self.idle_time = 30 else: self.count_down_time = 5 self.image_display_time = 3 self.montage_display_time = 15 self.idle_time = 240 self.print_count = print_count self.printer = printer self.upload_to = upload_to self.output_dir = image_dest self.size = None self.fullscreen = fullscreen self.events = [] self.current_session = None
def createLightView(self, lightNum, lightPos, directionFront, upVector): self.__lightNum = lightNum cam = Camera() cam.setCameraFront(*directionFront) cam.setCameraPosition(*lightPos) cam.setWorldUp(*upVector) #cam.linearMove(CamMovement.FORWARD, 0.001) # little trick to focus the target point cam.updateCamera() self.__lightView = cam return self.__lightView
def detect_balls_by_radius(): """ get coordinates and distance of all balls """ camera = Camera(0, 648.5256168410046, 0.340394) ball = ImageObject(0.22510163906500055 / 2) while True: ok, frame = camera.read() cv2.imshow('feed', pipeline(frame)) cnts = list(pipeline_cnts(frame)) d = [] d_norm = [] rs = [] centers = [] if len(cnts) > 0: for cnt in cnts: to_continue = False center, r = cv2.minEnclosingCircle(cnt) #if p_ball(cv2.contourArea(cnt), r) # 0.0: # continue for i in range(len(rs)): if is_circle_invalid(center1=center, r1=r, center2=centers[i], r2=rs[i]): to_continue = True break if to_continue: continue centers.append(center) rs.append(r) cv2.circle(frame, tuple(map(int, center)), int(r), (0, 255, 0), 2) cv2.circle(frame, tuple(map(int, center)), 2, (0, 0, 255), 2) area = np.sqrt(np.pi) * r d_norm.append(ball.distance_by_params(camera, area)) d.append(ball.location2d_by_params(camera, area, center)) cv2.circle(frame, (frame.shape[1] // 2, frame.shape[0] // 2), 2, (255, 0, 0), 2) cv2.imshow('original', frame) k = cv2.waitKey(1) & 0xFF if k == ord('d'): print(d) print(d_norm) if k == ord('c'): cv2.destroyAllWindows() break
def sample_camera(): cam = Camera(0) # settings if not os.path.exists("settings.yaml"): print("Error: settings file not found!") exit() config = yaml.load(open("settings.yaml")) # fps fps = config["fps"] # time_to_wait = 1./fps # c = 0 # while c < 10000: # c += 1 # start_time = time.time() # camera stuff # cam.acquire_frame() # cam.visualize_current_frame() # cam.save_current_frame() # cam.save_current_frame_video() # elapsed_time = time.time() - start_time # if time_to_wait - elapsed_time > 0: # time.sleep(time_to_wait - elapsed_time) # cam.close_video() cam.run() time.sleep(2) print("Shutting down...") cam.stop() time.sleep(2) print("Restarting...") cam.run()
def __init__(self, data_dir=r'D:\\deverett', wf_calib_path=r'C:\\WF\\calibration.npz'): # Make app self.app = wx.App(False) self.view = View(None) self.view.Bind(wx.EVT_CLOSE, self.evt_close) # Button bindings self.view.add_sub_button.Bind(wx.EVT_BUTTON, self.evt_addsub) self.view.but_load.Bind(wx.EVT_BUTTON, self.evt_load) self.view.but_reg.Bind(wx.EVT_BUTTON, self.evt_reg) self.view.but_freg.Bind(wx.EVT_BUTTON, self.evt_freg) self.view.but_save.Bind(wx.EVT_BUTTON, self.evt_save) # load initial info self.data_dir = data_dir subs = os.listdir(self.data_dir) self.view.add_sub(subs) try: with np.load(wf_calib_path) as cf: self.ppm_y = cf['pix_per_micron_y'] self.ppm_x = cf['pix_per_micron_x'] except FileNotFoundError: raise Exception('Calibration file not found. Please calibrate before registering.') # runtime self.cam = Camera() self.mp285 = MP285() self.current_sub = None self.register_mode = None self.result = None self.update() # Run self.app.MainLoop()
class PhotoBooth(object): def __init__(self, image_dest, fullscreen, debug, webcam, print_count, printer, upload_to): self.debug = debug if debug: self.camera = DebugCamera() elif webcam: self.camera = WebcamCamera() else: self.camera = Camera() if self.debug: self.count_down_time = 2 self.image_display_time = 3 self.montage_display_time = 8 self.idle_time = 30 else: self.count_down_time = 5 self.image_display_time = 3 self.montage_display_time = 15 self.idle_time = 240 self.print_count = print_count self.printer = printer self.upload_to = upload_to self.output_dir = image_dest self.size = None self.fullscreen = fullscreen self.events = [] self.current_session = None def capture_preview(self): picture = self.camera.capture_preview() if self.size: picture = pygame.transform.scale(picture, self.size) picture = pygame.transform.flip(picture, True, False) return picture def display_preview(self): picture = self.capture_preview() self.main_surface.blit(picture, (0, 0)) def display_image(self, image_name): picture = self.load_image(image_name) picture = pygame.transform.scale(picture, self.size) self.main_surface.blit(picture, (0, 0)) def start(self): pygame.init() pygame.mouse.set_visible(False) self.clock = pygame.time.Clock() self.add_button_listener() if self.fullscreen: pygame.display.set_mode((0, 0), pygame.FULLSCREEN) else: info = pygame.display.Info() pygame.display.set_mode((info.current_w/2, info.current_h/2)) self.main_surface = pygame.display.get_surface() self.size = self.main_surface.get_size() while self.main_loop(): pass self.camera.sleep() def main_loop(self): pygame.event.clear() self.clock.tick(25) if len(self.events) > 10: self.events = self.events[:10] pygame.display.flip() button_press = self.space_pressed() or self.button.is_pressed() if self.current_session: self.current_session.do_frame(button_press) if self.current_session.idle(): self.current_session = None self.camera.sleep() elif self.current_session.finished(): # Start a new session self.current_session = PhotoSession(self) elif button_press: # Start a new session self.current_session = PhotoSession(self) else: self.wait() return self.check_for_quit_event() def wait(self): self.main_surface.fill((0, 0, 0)) self.render_text_centred('Press the button to start!') def render_text_centred(self, *text_lines): location = self.main_surface.get_rect() font = pygame.font.SysFont(pygame.font.get_default_font(), 142) rendered_lines = [font.render(text, 1, (210, 210, 210)) for text in text_lines] line_height = font.get_linesize() middle_line = len(text_lines) / 2.0 - 0.5 for i, line in enumerate(rendered_lines): line_pos = line.get_rect() lines_to_shift = i - middle_line line_pos.centerx = location.centerx line_pos.centery = location.centery + lines_to_shift * line_height self.main_surface.blit(line, line_pos) def render_text_bottom(self, text, size=142): location = self.main_surface.get_rect() font = pygame.font.SysFont(pygame.font.get_default_font(), size) line = font.render(text, 1, (210, 210, 210)) line_height = font.get_linesize() line_pos = line.get_rect() line_pos.centerx = location.centerx line_pos.centery = location.height - 2 * line_height self.main_surface.blit(line, line_pos) def capture_image(self, file_name): file_path = os.path.join(self.output_dir, file_name) logger.info("Capturing image to: %s", file_path) self.camera.capture_image(file_path) if self.upload_to: upload_image_async(self.upload_to, file_path) def display_camera_arrow(self, clear_screen=False): if clear_screen: self.main_surface.fill((0, 0, 0)) arrow = pygame.Surface((300, 300), flags=pygame.SRCALPHA) pygame.draw.polygon(arrow, (255, 255, 255), ((100, 0), (200, 0), (200, 200), (300, 200), (150, 300), (0, 200), (100, 200))) # TODO: Update the coordinates above instead of this arrow = pygame.transform.flip(arrow, False, True) x = (self.size[0] - 300) / 2 self.main_surface.blit(arrow, (x, 20)) def load_image(self, file_name): if self.debug: image_path = "test.jpg" else: image_path = os.path.join(self.output_dir, file_name) return pygame.image.load(image_path) def save_and_print_combined(self, out_name, images): logger.info("Saving image: %s", out_name) out_path = os.path.join(self.output_dir, out_name) first_size = self.load_image(images[0]).get_size() padding_pxls = int(PADDING_PERCENT / 100.0 * first_size[0]) logger.debug("Padding: %s", padding_pxls) size = ((first_size[0] - padding_pxls)/2, (first_size[1] - padding_pxls)/2) logger.debug("Image size: %s", size) combined = pygame.Surface(first_size) combined.fill((255, 255, 255)) for count, image_name in enumerate(images): image = self.load_image(image_name) image = pygame.transform.scale(image, size) x_pos = (size[0] + padding_pxls) * (count % 2) y_pos = (size[1] + padding_pxls) * (1 if count > 1 else 0) combined.blit(image, (x_pos, y_pos)) logger.info("Save image to: %s", out_path) if not self.debug: pygame.image.save(combined, out_path) if self.print_count: if PRINT_IMAGE_SIZE: print_dir = os.path.join(self.output_dir, 'to_print') print_path = os.path.join(print_dir, out_name) convert_cmd = ['convert', out_path, '-resize', PRINT_IMAGE_SIZE + '^', '-gravity', 'center', '-extent', PRINT_IMAGE_SIZE, print_path] logger.info(' '.join(convert_cmd)) if not self.debug: if not os.path.exists(print_dir): os.makedirs(print_dir) call(convert_cmd) else: print_path = out_path self.print_image(print_path) def print_image(self, image_path): printing_cmd = ["lpr"] if self.printer: printing_cmd += ["-P", self.printer] printing_cmd += ["-#", str(self.print_count), image_path] logger.info(' '.join(printing_cmd)) if not self.debug: call(printing_cmd) def add_button_listener(self): self.button = Button() def check_key_event(self, *keys): self.events += pygame.event.get(pygame.KEYUP) for event in self.events: if event.dict['key'] in keys: self.events = [] return True return False def space_pressed(self): return self.check_key_event(pygame.K_SPACE) def check_for_quit_event(self): return not self.check_key_event(pygame.K_q, pygame.K_ESCAPE) \ and not pygame.event.peek(pygame.QUIT)
from cameras import Camera from mp285 import MP285 import itertools as it import numpy as np import pylab as pl import cv2 from scipy.stats import linregress calib_path = r'C:\\WF\\calibration.npz' mp285 = MP285() cam = Camera() mp285.zero(warn=False) img0 = cam.get(n=5) ims_x = [] ims_y = [] step = 50 pos = np.arange(-5*step,5*step+1,step) for i,p in enumerate(pos): mp285.goto([p,0,0]) #X ims_x.append(cam.get(n=5)) pl.subplot(4,4,i+1) pl.imshow(cam.get(n=5)) for i,p in enumerate(pos): mp285.goto([0,p,0]) #Y ims_y.append(cam.get(n=5)) mp285.goto([0,0,0]) cam.end() mp285.end()
class Controller: REFRESH_INTERVAL = 100 #ms NEW,EXISTS = 0,1 def __init__(self, data_dir=r'D:\\deverett', wf_calib_path=r'C:\\WF\\calibration.npz'): # Make app self.app = wx.App(False) self.view = View(None) self.view.Bind(wx.EVT_CLOSE, self.evt_close) # Button bindings self.view.add_sub_button.Bind(wx.EVT_BUTTON, self.evt_addsub) self.view.but_load.Bind(wx.EVT_BUTTON, self.evt_load) self.view.but_reg.Bind(wx.EVT_BUTTON, self.evt_reg) self.view.but_freg.Bind(wx.EVT_BUTTON, self.evt_freg) self.view.but_save.Bind(wx.EVT_BUTTON, self.evt_save) # load initial info self.data_dir = data_dir subs = os.listdir(self.data_dir) self.view.add_sub(subs) try: with np.load(wf_calib_path) as cf: self.ppm_y = cf['pix_per_micron_y'] self.ppm_x = cf['pix_per_micron_x'] except FileNotFoundError: raise Exception('Calibration file not found. Please calibrate before registering.') # runtime self.cam = Camera() self.mp285 = MP285() self.current_sub = None self.register_mode = None self.result = None self.update() # Run self.app.MainLoop() def evt_close(self, evt): self.update_timer.Stop() self.cam.end() self.mp285.end() cv2.destroyAllWindows() pl.close('all') self.view.Destroy() def update(self): self.imshow('Live Camera',self.cam.get()) self.update_timer = wx.CallLater(self.REFRESH_INTERVAL, self.update) def get_paths(self, sub): if not os.path.exists(os.path.join(self.data_dir, self.current_sub)): os.mkdir(os.path.join(self.data_dir, self.current_sub)) subdir = os.path.join(self.data_dir, self.current_sub) fov_files = [re.match('fov_(\d*)_.*.npy',f) for f in os.listdir(subdir)] date = time.strftime('%Y%m%d') if not any(fov_files): idx = -1 cpath = None else: idx = max([int(i.groups()[0]) for i in fov_files]) cpath = os.path.join(self.data_dir,self.current_sub,'fov_{:03d}_{}.npy'.format(idx, date)) npath = os.path.join(self.data_dir,self.current_sub,'fov_{:03d}_{}.npy'.format(idx+1, date)) return cpath,npath def evt_load(self, evt): sub = self.view.sub_box.GetSelection() if sub == wx.NOT_FOUND: return self.current_sub = self.view.sub_names[sub] self.current_path,self.next_path = self.get_paths(self.current_sub) if self.current_path: self.register_mode = self.EXISTS self.template = np.load(self.current_path) elif not self.current_path: self.register_mode = self.NEW self.template = np.zeros(self.cam.frame_shape) self.imshow('Existing Template: {}'.format(self.current_sub),self.template) self.result = None def evt_reg(self, evt): if self.register_mode is None: return if self.register_mode == self.NEW: before_reg = self.cam.get(n=5) result = self.cam.get(n=5) score = 1.0 elif self.register_mode == self.EXISTS: before_reg = self.cam.get(n=5) self.update_timer.Stop() reg,score = register_imgs(self.template, self.cam) apply_registration(reg, self.mp285, np.array([self.ppm_x,self.ppm_y])) result = self.cam.get(n=5) self.update_timer = wx.CallLater(self.REFRESH_INTERVAL, self.update) pl.subplot(2,2,1) self.plshow('Loaded Template: {}'.format(self.current_sub), self.template) pl.subplot(2,2,2) self.plshow('Original FOV today: {}'.format(self.current_sub), before_reg) pl.subplot(2,2,3) self.plshow('Adjusted FOV (and new template): {}'.format(self.current_sub), result) pl.subplot(2,2,4) diff = np.abs(result-self.template) diff = diff.astype(float) self.plshow('Difference b/t old and new fov\nScore: {:0.3f}'.format(score), diff) self.register_mode = None self.result = result dlg = wx.MessageDialog(self.view, 'Remember to save.', 'Registered.', wx.OK) _ = dlg.ShowModal() dlg.Destroy() def evt_save(self, evt): if self.result is None: return np.save(self.next_path, self.result) def evt_freg(self, evt): if self.register_mode is None: return if self.register_mode == self.NEW: before_reg = self.cam.get(n=5) result = self.cam.get(n=5) score = 1.0 elif self.register_mode == self.EXISTS: before_reg = self.cam.get(n=5) self.update_timer.Stop() # note no registration process occurs here; this is forced registration result = self.cam.get(n=5) self.update_timer = wx.CallLater(self.REFRESH_INTERVAL, self.update) pl.subplot(2,2,1) self.plshow('Loaded Template: {}'.format(self.current_sub), self.template) pl.subplot(2,2,2) self.plshow('Original FOV today: {}'.format(self.current_sub), before_reg) pl.subplot(2,2,3) self.plshow('Adjusted FOV (and new template): {}'.format(self.current_sub), result) pl.subplot(2,2,4) diff = np.abs(result-self.template) diff = diff.astype(float) self.plshow('Difference b/t old and new fov', diff) self.register_mode = None self.result = result def evt_addsub(self, evt): dlg = wx.TextEntryDialog(self.view, message='Enter new subject name:') ret = dlg.ShowModal() if ret == wx.ID_OK: self.view.add_sub(dlg.GetValue().strip().lower()) else: pass def imshow(self, win, im): im = cv2.resize(im, tuple(np.array(im.shape[::-1])/3)) cv2.imshow(win, im) def plshow(self, txt, im): pl.imshow(im, cmap='gray') pl.axis('off') pl.title(txt)
from cameras import Camera frame_rate = 30 #15,30,40,50,60,75,100,125 -- some are specific to one resolution frame_shape = [320,240] dur = raw_input('Enter video duration: ') dur = float(dur) name = '' while len(name) == 0: name = raw_input('Enter video name: ') name = 'data\\'+name print('Acquiring...') cam = Camera(fps=frame_rate, frame_shape=frame_shape) cam.run(dur=dur, name=name) print('Acquisition complete.')
import cv2 from cameras import Camera, Cellphone motorola_one = Cellphone('moto_one', 'http://192.168.0.116:8080/shot.jpg') samsung_edge = Cellphone('samsung_edge', 'http://192.168.0.2:8080/shot.jpg') webcam = Camera('webcam') print(Camera.count()) print("\n" "+-------------------------------------+\n" "| Que dispositivo desea usar? |\n" "+-------------------------------------+\n" "| --> 1-Laptop's webcam (default) |\n" "| --> 2-Motorola_one |\n" "| --> 3-Samsung Edge |\n" "| --> 4-Otro |\n" "+-------------------------------------+\n") device = input("Escriba aquí: ") if device == "4": name = input("Enter the name of the Cellphone:") url = input("Paste the url of IP Webcam") new_phone = Cellphone(name, url) new_phone.get_display() elif device == "3": samsung_edge.get_display() elif device == "2": motorola_one.get_display() elif device == "1": video = cv2.VideoCapture(0) webcam.get_display(video)
from flask import Flask, render_template, request from cameras import Camera import yaml import os import time app = Flask(__name__) camera = Camera(0) @app.route("/") def main(): return render_template("index.html") @app.route("/button_action", methods=['GET', 'POST']) def button_action(): print('debug') if request.method == 'POST': if request.form['action'] == 'start': handle_camera('start') status = "start" elif request.form['action'] == 'stop': handle_camera('stop') status = "stop" else: return "Not defined" l = ['a', 'b'] # return render_template("index.html", status=status, llist=l) return render_template("index.html", status=status)
cv2.destroyAllWindows() if self.save_on: self.writer.release() time_name = os.path.join(self.dirr, self.run_name+'-timestamps.json') with open(time_name, 'w') as f: f.write("%s"%json.dumps(self.time)) def next_frame(self, t0): frame, timestamp = self.cam.read() if self.show: showframe = frame.copy() cv2.putText(showframe, "%0.3f"%(timestamp-t0), (10,60), cv2.FONT_HERSHEY_SIMPLEX, 2, (255,255,255)) cv2.imshow('Camera', showframe) c = cv2.waitKey(1) if self.save_on: self.time.append(timestamp) self.writer.write(frame) return c def go(self): t = time.time() c = None while time.time()-t < self.duration and c!=ord('q'): c = self.next_frame(t) c = self.next_frame(t) self.end() if __name__ == '__main__': m = Monitor(cameras=Camera(), show=True, save_on=False) m.go()