def __init__(self): self.items = {} self.items["button"] = {} self.items["labels"] = {} self.items["button"]["github"] = TextButton("Github Repo", 212, 382) self.items["button"]["return"] = TextButton("Return", 212, 466) self.items["labels"]["label1"] = Label("Made by", 32, 261, 231) self.items["labels"]["label2"] = Label("Pedro Perpetua", 32, 172, 268)
def detect_lp(output_dir, loaded_models, Iorig_name): imgs_paths = glob('%s/%s_*car.png' % (output_dir, Iorig_name)) print('Searching for license plates...') for i, img_path in enumerate(imgs_paths): bname = splitext(basename(img_path))[0] lp_net, lp_meta, lp_threshold = loaded_models[1] R, _ = detect(lp_net, lp_meta, img_path.encode('utf-8'), thresh=lp_threshold) if len(R): Iorig = cv2.imread(img_path) WH = np.array(Iorig.shape[1::-1], dtype=float) Llp = [] for i, r in enumerate(R): cx, cy, w, h = (np.array(r[2]) / np.concatenate( (WH, WH))).tolist() tl = np.array([cx - w / 2., cy - h / 2.]) br = np.array([cx + w / 2., cy + h / 2.]) label = Label(0, tl, br) Ilp = crop_region(Iorig, label) Llp.append(label) cv2.imwrite('%s/%s_lp.png' % (output_dir, bname), Ilp) lwrite('%s/%s_lp.txt' % (output_dir, bname), Llp) else: print('No license plate found')
def detect_vehicles(self, img_path): vehicle_threshold = 0.5 classes = ['car', 'bus', 'truck', 'motorcycle'] results, _ = dn.detect(self.vehicle_net, self.vehicle_meta, img_path, thresh=vehicle_threshold) results = [ result for result in results if result[0].decode('utf-8') in classes ] vehicles = [] if len(results): image = cv2.imread(img_path) WH = np.array(image.shape[1::-1], dtype=float) for i, result in enumerate(results): cx, cy, w, h = (np.array(result[2]) / np.concatenate( (WH, WH))).tolist() tl = np.array([cx - w / 2., cy - h / 2.]) br = np.array([cx + w / 2., cy + h / 2.]) label = Label(0, tl, br) vehicle = crop_region(image, label) results[i] = (result[0], result[1], result[2], vehicle) vehicles.append(label) return vehicles
def on_any_event(event): if event.is_directory: return None elif event.event_type == 'created': # Take any action here when a file is first created. print("Received created event - %s." % event.src_path) try: img_path = event.src_path print('\tScanning %s' % img_path) bname = basename(splitext(img_path)[0]) R, _ = detect(vehicle_net, vehicle_meta, img_path, thresh=lp_threshold) R = [r for r in R if r[0] in ['vehicle registration plate']] print('\t\t%d plates found' % len(R)) if len(R): Iorig = cv2.imread(img_path) WH = np.array(Iorig.shape[1::-1], dtype=float) Lcars = [] for i, r in enumerate(R): cx, cy, w, h = (np.array(r[2]) / np.concatenate( (WH, WH))).tolist() tl = np.array([cx - w / 2., cy - h / 2.]) br = np.array([cx + w / 2., cy + h / 2.]) label = Label(0, tl, br) Icar = crop_region(Iorig, label) Lcars.append(label) height, width, _ = Icar.shape print(height, width) if height > 24: cv2.imwrite( '%s/%s_%dplate.png' % (output_dir, bname, i), Icar) else: print( 'plate likely too small to OCR, high change of FP' ) if os.path.exists(img_path): os.remove(img_path) else: if os.path.exists(img_path): os.remove(img_path) except: traceback.print_exc() sys.exit(1) elif event.event_type == 'modified': # Taken any action here when a file is modified. print("Received modified event - %s." % event.src_path)
def vehicle_detect(vehicle_net, vehicle_meta, vehicle_threshold, img): print ('Searching for vehicles using YOLO...') R,_ = detect2(vehicle_net, vehicle_meta, img, thresh=vehicle_threshold) R = [r for r in R if r[0] in [b'car',b'bus']] print ('\t\t%d cars found' % len(R)) Icars = [] Lcars = [] Tcars = [] Scars = [] Pcars = [] if len(R): Iorig = img WH = np.array(Iorig.shape[1::-1],dtype=float) for i,r in enumerate(R): # print ('\t\t\t%d %d %4.2f' % (r[2][2], r[2][3], r[1])) cx,cy,w,h = (np.array(r[2])/np.concatenate( (WH,WH) )).tolist() tl = np.array([cx - w/2., cy - h/2.]) br = np.array([cx + w/2., cy + h/2.]) label = Label(0,tl,br) Icar = crop_region(Iorig,label) if (r[2][2] > vehicle_width_threshold and r[2][3] > vehicle_height_threshold): Icars.append(Icar) Lcars.append(label) Tcars.append(r[0]) Scars.append(r[1]) Pcars.append(r[2]) #cv2.imwrite('%s/%dcar.png' % (car_img_dir,i),Icar) #lwrite('%s/cars.txt' % (car_img_dir),Lcars) print ('\t\t%d cars chosen' % len(Icars)) return Icars, Lcars, Tcars, Scars, Pcars
def find_vehicle_one_img(img_path, veh_net, veh_meta, out_dir, veh_thd): st = time.time() print '\tScanning %s' % img_path bname = basename(splitext(img_path)[0]) R, _ = dn.detect(veh_net, veh_meta, img_path, thresh=veh_thd) # R: [name, prob, [x center, y center, width, height]] R = [r for r in R if r[0] in ['car', 'bus']] out_img = [] out_label_f = "" if len(R): Iorig = cv2.imread(img_path) WH = np.array(Iorig.shape[1::-1], dtype=float) Lcars = [] for i, r in enumerate(R): cx, cy, w, h = (np.array(r[2]) / np.concatenate((WH, WH))).tolist() tl = np.array([cx - w / 2., cy - h / 2.]) br = np.array([cx + w / 2., cy + h / 2.]) label = Label(0, tl, br) Icar = crop_region(Iorig, label) Lcars.append(label) p_img = '%s/%s_%dcar.png' % (out_dir, bname, i) cv2.imwrite(p_img, Icar) out_img.append(p_img) out_label_f = '%s/%s_cars.txt' % (out_dir, bname) lwrite(out_label_f, Lcars) print '\t\t%d cars found, runtime: %.1fs' % (len(R), time.time() - st) return out_img, out_label_f
def genOutput(img_path, output_dir, bname): I = cv2.imread(img_path) detected_cars_labels = '%s/%s_cars.txt' % (output_dir, bname) Lcar = lread(detected_cars_labels) sys.stdout.write('%s' % bname) if Lcar: for i, lcar in enumerate(Lcar): draw_label(I, lcar, color=YELLOW, thickness=3) lp_label = '%s/%s_%dcar_lp.txt' % (output_dir, bname, i) lp_label_str = '%s/%s_%dcar_lp_str.txt' % (output_dir, bname, i) if isfile(lp_label): Llp_shapes = readShapes(lp_label) pts = Llp_shapes[0].pts * lcar.wh().reshape( 2, 1) + lcar.tl().reshape(2, 1) ptspx = pts * np.array(I.shape[1::-1], dtype=float).reshape( 2, 1) draw_losangle(I, ptspx, RED, 3) if isfile(lp_label_str): with open(lp_label_str, 'r') as f: lp_str = f.read().strip() llp = Label(0, tl=pts.min(1), br=pts.max(1)) write2img(I, llp, lp_str) sys.stdout.write(',%s' % lp_str) cv2.imwrite('%s/%s_output.png' % (output_dir, bname), I, [int(cv2.IMWRITE_PNG_COMPRESSION), 9])
def detect_vehicle(img_path, output_dir, loaded_models, bname): vehicle_net, vehicle_meta, vehicle_threshold = loaded_models[0] R, _ = detect(vehicle_net, vehicle_meta, img_path.encode('utf-8'), thresh=vehicle_threshold) R = [r for r in R if r[0].decode(encoding='utf-8') in ['car']] print('%d cars found' % len(R)) if len(R): Iorig = cv2.imread(img_path) WH = np.array(Iorig.shape[1::-1], dtype=float) Lcars = [] for i, r in enumerate(R): cx, cy, w, h = (np.array(r[2]) / np.concatenate((WH, WH))).tolist() tl = np.array([cx - w / 2., cy - h / 2.]) br = np.array([cx + w / 2., cy + h / 2.]) label = Label(0, tl, br) Icar = crop_region(Iorig, label) Lcars.append(label) cv2.imwrite('%s/%s_%dcar.png' % (output_dir, bname, i), Icar) lwrite('%s/%s_cars.txt' % (output_dir, bname), Lcars)
def augment_sample(I,pts, dim_w, dim_h, cls): maxsum,maxangle = 50,np.array([20.,20.,25.]) angles = np.random.rand(3)*maxangle if angles.sum() > maxsum: angles = (angles/angles.sum())*(maxangle/maxangle.sum()) I = im2single(I) iwh = getWH(I.shape) # codigo original # whratio = random.uniform(2., 4.) # wsiz = random.uniform(dim * .2, dim * 1.) # carro if cls=='0': whratio = random.uniform(2.75, 3.25) wsiz = random.uniform(dim_w * .2, dim_w * 0.7) else: whratio = random.uniform(0.7, 1.2) wsiz = random.uniform(dim_w * .2, dim_w * 0.7) # whratio = 1. # wsiz = random.uniform(dim_w*.2, dim_w*1.) # moto # whratio = random.uniform(0.7, 1.2) # wsiz = random.uniform(dim_w * .3, dim_w * 0.7) hsiz = wsiz/whratio dx = random.uniform(0.,dim_w - wsiz) dy = random.uniform(0.,dim_h - hsiz) pph = getRectPts(dx,dy,dx+wsiz,dy+hsiz) pts = pts*iwh.reshape((2,1)) T = find_T_matrix(pts2ptsh(pts),pph) H = perspective_transform((dim_w,dim_h),angles=angles) H = np.matmul(H,T) Iroi,pts = project(I,H,pts,dim_w, dim_h) # hsv_mod = np.random.rand(3).astype('float32') # hsv_mod = (hsv_mod - .5)*.3 # hsv_mod[0] *= 360 # Iroi = hsv_transform(Iroi,hsv_mod) Iroi = np.clip(Iroi,0.,1.) pts = np.array(pts) # if random.random() > .5: # Iroi,pts = flip_image_and_pts(Iroi,pts) tl,br = pts.min(1),pts.max(1) llp = Label(0,tl,br) return Iroi,llp,pts
def __init__(self, highscore_handler): self.items = {} self.items["button"] = {} self.items["days"] = {} self.items["times"] = {} self.items["points"] = {} scores = highscore_handler.get_top_scores() self.items["days"]["1st"] = Label(scores[0]["day"], 24, 210, 205) self.items["times"]["1st"] = Label(scores[0]["time"], 24, 210, 237) self.items["points"]["1st"] = Label(scores[0]["points"], 38, 426, 214) self.items["days"]["2nd"] = Label(scores[1]["day"], 24, 210, 285) self.items["times"]["2nd"] = Label(scores[1]["time"], 24, 210, 317) self.items["points"]["2nd"] = Label(scores[1]["points"], 38, 426, 294) self.items["days"]["3rd"] = Label(scores[2]["day"], 24, 210, 365) self.items["times"]["3rd"] = Label(scores[2]["time"], 24, 210, 397) self.items["points"]["3rd"] = Label(scores[2]["points"], 38, 426, 374) self.items["button"]["return"] = TextButton("Return", 212, 466)
def draw_without_car(self, img, Llp_shapes, Llp_str, wh, tl): for i in range(len(Llp_shapes)): if Llp_shapes[i] is not None: pts = Llp_shapes[i].pts * wh.reshape(2, 1) + tl.reshape(2, 1) ptspx = pts * np.array(img.shape[1::-1], dtype=float).reshape( 2, 1) draw_losangle(img, ptspx, RED, 3) if Llp_str[i] is not None: llp = Label(0, tl=pts.min(1), br=pts.max(1)) write2img(img, llp, Llp_str[i]) return img
def on_any_event(event): if event.is_directory: return None elif event.event_type == 'created': # Take any action here when a file is first created. print("Received created event - %s." % event.src_path) try: print('\tScanning %s' % event.src_path) try: img_path = event.src_path print('\tScanning %s' % img_path) bname = basename(splitext(img_path)[0]) R, _ = detect(vehicle_net, vehicle_meta, img_path.encode('utf-8'), thresh=vehicle_threshold) R = [r for r in R if r[0] in ['car', 'bus']] print('\t\t%d cars found' % len(R)) if len(R): Iorig = cv2.imread(img_path) WH = np.array(Iorig.shape[1::-1], dtype=float) Lcars = [] for i, r in enumerate(R): cx, cy, w, h = (np.array(r[2]) / np.concatenate( (WH, WH))).tolist() tl = np.array([cx - w / 2., cy - h / 2.]) br = np.array([cx + w / 2., cy + h / 2.]) label = Label(0, tl, br) Icar = crop_region(Iorig, label) Lcars.append(label) cv2.imwrite( '%s/%s_%dcar.png' % (output_dir, bname, i), Icar) except: traceback.print_exc() sys.exit(1) except: traceback.print_exc() sys.exit(1)
def vehicle_detection(img_path, output_dir): try: if not isdir(output_dir): makedirs(output_dir) bname = basename(splitext(img_path)[0]) plates = [] # Vehicle detection R, _ = detect(vehicle_net, vehicle_meta, img_path, thresh=vehicle_threshold) R = [r for r in R if r[0] in ['car', 'bus', 'motorbike']] # print '\t\t%d cars found' % len(R) if not len(R): return ("", plates) Iorig = cv2.imread(img_path) WH = np.array(Iorig.shape[1::-1], dtype=float) Lcars = [] for i, r in enumerate(R): cx, cy, w, h = (np.array(r[2]) / np.concatenate((WH, WH))).tolist() tl = np.array([cx - w / 2., cy - h / 2.]) br = np.array([cx + w / 2., cy + h / 2.]) label = Label(0, tl, br) Icar = crop_region(Iorig, label) Lcars.append(label) carImagePath = '%s/%s_%dcar.png' % (output_dir, bname, i) cv2.imwrite(carImagePath, Icar) #print("CarImagePath: ", carImagePath) # LP detection LPImagePath = LPDection(carImagePath) if LPImagePath: lp_str = OCRDection(LPImagePath) if lp_str: plates.append(lp_str) lwrite('%s/%s_cars.txt' % (output_dir, bname), Lcars) # draw yellow box around the cars and red box around license plates genOutput(img_path, output_dir, bname) return ('%s/%s_output.png' % (output_dir, bname), plates) except: traceback.print_exc() return ("", plates)
class TestLabel: def setup(self): self.labeler = Label() def teardown(self): pass def test_label_benign_domain(self): actual = self.labeler.label("google.com") assert actual == 0 def test_check_for_benign_domain(self): actual = self.labeler.check_for_benign_domain("google.com") assert actual == True def test_label_malicious_domain(self): actual = self.labeler.label("creativebookmark.com") assert actual == 1 def test_check_for_malicious_domain(self): actual = self.labeler.check_for_malicious_domain("creativebookmark.com") assert actual == True def test_case_insensitivity(self): actual = self.labeler.label("crEATivebookmark.com") assert actual == 1 def test_get_domain_variations(self): actual = self.labeler.get_domain_variations("google.com") assert "https://www.google.com" in actual assert "http://www.google.com" in actual assert "www.google.com" in actual def test_list_lower(self): actual = self.labeler.list_lower(["ABC", "abc", "CDE", "FGE"]) assert actual == ["abc", "abc", "cde", "fge"] def test_get_domain_labels(self): actual = self.labeler.get_domain_labels({"google.com": 0, "creativebookmark.com": 1, "crEATivebookmark.com": 2,"test.com": 3}) assert actual[0,0] == 0 assert actual[0,1] == 1 assert actual[1,0] == 1 assert actual[1,1] == 0 assert actual[2,0] == 1 assert actual[2,1] == 0 assert actual[3,0] == 0 assert actual[3,1] == 1
def gen_output(output_dir): YELLOW = (0, 255, 255) RED = (0, 0, 255) bname = splitext(basename(img_path))[0] I = cv2.imread(img_path) detected_cars_labels = '%s/%s_cars.txt' % (output_dir, bname) Lcar = lread(detected_cars_labels) if Lcar: for i, lcar in enumerate(Lcar): draw_label(I, lcar, color=YELLOW, thickness=3) lp_label = '%s/%s_%dcar_lp.txt' % (output_dir, bname, i) lp_label_str = '%s/%s_%dcar_lp_str.txt' % (output_dir, bname, i) C = cv2.imread('%s/%s_%dcar.png' % (output_dir, bname, i)) if isfile(lp_label): Llp = lread(lp_label) for j, llp in enumerate(Llp): draw_label(I, llp, color=RED, thickness=3, lp=True, lcar=lcar, C=C) if isfile(lp_label_str): with open(lp_label_str, 'r') as f: lp_str = f.read().strip() cwh = np.array(C.shape[1::-1]).astype(float) iwh = np.array(I.shape[1::-1]).astype(float) tl = tuple( np.add((llp.tl() * cwh).tolist(), (lcar.tl() * iwh).tolist()) / iwh) br = tuple( np.add((llp.br() * cwh).tolist(), (lcar.tl() * iwh).tolist()) / iwh) temp_label = Label(0, tl=tl, br=br) write2img(I, temp_label, lp_str) return I
def sample_validate(image_abs_path, gt_file): L = readShapes(gt_file)[0] pts_transformed = L.pts model_stride = 16.0 image_ndarray = cv2.imread(image_abs_path) tl, br = pts_transformed.min(1), pts_transformed.max(1) llp = Label(0, tl, br) YY, is_there_plate = labels2output_map(llp, pts_transformed, 304, 304, model_stride, L.cls, image_abs_path) print('There is place: %s | Class %s ' % (str(is_there_plate), L.cls)) print('Car ') print(np.matrix(YY[..., 0])) print('Non-object') print(np.matrix(YY[..., 10])) print('Moto') print(np.matrix(YY[..., 9]))
def augment_sample(I,pts,dim): maxsum,maxangle = 120,np.array([80.,80.,45.]) angles = np.random.rand(3)*maxangle if angles.sum() > maxsum: angles = (angles/angles.sum())*(maxangle/maxangle.sum()) I = im2single(I) # /255.0 归一化 iwh = getWH(I.shape) #得到宽高 whratio = random.uniform(2.,4.) # 随即取一个2-4的值作为宽高比 wsiz = random.uniform(dim*.2,dim*1.) # 宽取0.2*208 到 208之间 hsiz = wsiz/whratio dx = random.uniform(0.,dim - wsiz) dy = random.uniform(0.,dim - hsiz) #下面涉及到整个变换 # In the first 3 lines, the original corner points are transformed into a rectangular bounding box with aspect ratio # varying between 2:1 and 4:1. In other words, T matrix rectifies the LP with a random aspect ratio. Then, pph = getRectPts(dx,dy,dx+wsiz,dy+hsiz) pts = pts*iwh.reshape((2,1)) #将点恢复到真实坐标值 T = find_T_matrix(pts2ptsh(pts),pph) #in the next two lines, a perspective transformation with random rotation (H) is combined with T to #generate the final transformation. H = perspective_transform((dim,dim),angles=angles) H = np.matmul(H,T) Iroi,pts = project(I,H,pts,dim) hsv_mod = np.random.rand(3).astype('float32') hsv_mod = (hsv_mod - .5)*.3 hsv_mod[0] *= 360 Iroi = hsv_transform(Iroi,hsv_mod) Iroi = np.clip(Iroi,0.,1.) pts = np.array(pts) if random.random() > .5: Iroi,pts = flip_image_and_pts(Iroi,pts) tl,br = pts.min(1),pts.max(1) llp = Label(0,tl,br) return Iroi,llp,pts
def augment_sample(I,pts,dim): maxsum,maxangle = 120,np.array([80.,80.,45.]) angles = np.random.rand(3)*maxangle if angles.sum() > maxsum: angles = (angles/angles.sum())*(maxangle/maxangle.sum()) # chuyển qua ma trận float32, chia cho 255 I = im2single(I) # Lấy w, h dạng ma trận iwh = getWH(I.shape) whratio = random.uniform(2.,4.) wsiz = random.uniform(dim*.2,dim*1.) hsiz = wsiz/whratio dx = random.uniform(0.,dim - wsiz) dy = random.uniform(0.,dim - hsiz) pph = getRectPts(dx,dy,dx+wsiz,dy+hsiz) # Lấy tọa độ thật pts = pts*iwh.reshape((2,1)) T = find_T_matrix(pts2ptsh(pts),pph) H = perspective_transform((dim,dim),angles=angles) H = np.matmul(H,T) Iroi,pts = project(I,H,pts,dim) hsv_mod = np.random.rand(3).astype('float32') hsv_mod = (hsv_mod - .5)*.3 hsv_mod[0] *= 360 Iroi = hsv_transform(Iroi,hsv_mod) Iroi = np.clip(Iroi,0.,1.) pts = np.array(pts) if random.random() > .5: Iroi,pts = flip_image_and_pts(Iroi,pts) # lấy giá trị tọa độ top-left, bot-right tl,br = pts.min(1),pts.max(1) llp = Label(0,tl,br) return Iroi,llp,pts
def draw(self, img, Lcars, Llp_shapes, Llp_str): for i, lcar in enumerate(Lcars): draw_label(img, lcar, color=YELLOW, thickness=3) if Llp_shapes[i] is not None: # print("Llp.shapes[i].pts: ", Llp_shapes[i].pts) pts = Llp_shapes[i].pts * lcar.wh().reshape( 2, 1) + lcar.tl().reshape(2, 1) # print("pts: ", pts) ptspx = pts * np.array(img.shape[1::-1], dtype=float).reshape( 2, 1) # print("ptspx: ", ptspx) draw_losangle(img, ptspx, RED, 3) if Llp_str[i] is not None: llp = Label(0, tl=pts.min(1), br=pts.max(1)) write2img(img, llp, Llp_str[i]) return img
def predict(self, img, bname): # bname = basename(splitext(img_path)[0]) # img = cv2.imread(img_path) # img = img_path.encode('utf-8') # print(img) output_dir = "output/tmp" R, _ = detect_image(self.vehicle_net, self.vehicle_meta, img, thresh=self.vehicle_threshold) # print(detect(vehicle_net, vehicle_meta, img ,thresh=vehicle_threshold)) # print("R :", [r for r in R if not math.isnan(r[2][0])]) # print("R: ", R[0][2][0]) R = [r for r in R if r[0].decode('utf-8') in ['car', 'bus']] print('\t\t{} cars found'.format(len(R))) cars_img = [] Lcars = [] if len(R): # Iorig = cv2.imread(img_path) Iorig = img WH = np.array(Iorig.shape[1::-1], dtype=float) for i, r in enumerate(R): cx, cy, w, h = (np.array(r[2]) / np.concatenate( (WH, WH))).tolist() tl = np.array([cx - w / 2., cy - h / 2.]) br = np.array([cx + w / 2., cy + h / 2.]) label = Label(0, tl, br) Icar = crop_region(Iorig, label) Lcars.append(label) # cv2.imwrite('{}/{}_{}car.png'.format(output_dir, bname, i), Icar) cars_img.append(Icar) # lwrite('{}/{}_cars.txt'.format(output_dir, bname), Lcars) return cars_img, Lcars
def detect_vehicle(self, img, filename): data = [] copy = img R, boxes, confidences, class_ids = self.vehicle.detect_objects(copy, str(filename).split('.')[0] + '.txt') if len(R): WH = np.array(copy.shape[1::-1], dtype=float) Lcars = [] for i, r in enumerate(R): cx, cy, w, h = (np.array(boxes[i])/np.concatenate((WH, WH))).tolist() tl = np.array([cx - w/2., cy - h/2.]) br = np.array([cx + w/2., cy + h/2.]) label = Label(0, tl, br) Lcars.append(label) data.append((cx, cy, w, h)) cv2.imwrite('%s/%s-car.png' % (self.output_dir, filename), copy) lwrite('%s/%s-car.txt' % (self.output_dir, filename), Lcars) return data
def generate_outputs(input_dir, output_dir): img_files = image_files_from_folder(input_dir) for img_file in img_files: bname = splitext(basename(img_file))[0] I = cv2.imread(img_file) detected_cars_labels = '%s/%s_cars.txt' % (output_dir, bname) Lcar = lread(detected_cars_labels) sys.stdout.write('%s' % bname) if Lcar: for i, lcar in enumerate(Lcar): draw_label(I, lcar, color=YELLOW, thickness=3) lp_label = '%s/%s_%dcar_lp.txt' % (output_dir, bname, i) lp_label_str = '%s/%s_%dcar_lp_str.txt' % (output_dir, bname, i) if isfile(lp_label): Llp_shapes = readShapes(lp_label) pts = Llp_shapes[0].pts * lcar.wh().reshape(2, 1) + lcar.tl().reshape(2, 1) ptspx = pts * np.array(I.shape[1::-1], dtype=float).reshape(2, 1) draw_losangle(I, ptspx, RED, 3) if isfile(lp_label_str): with open(lp_label_str, 'r') as f: lp_str = f.read().strip() llp = Label(0, tl=pts.min(1), br=pts.max(1)) write2img(I, llp, lp_str) sys.stdout.write(',%s' % lp_str) cv2.imwrite('%s/%s_output.png' % (output_dir, bname), I)
def car_detect(Iorig): Lcars=[] R = [] vehicle_threshold = .5 R = detect(vehicle_net, vehicle_meta, Iorig,thresh=vehicle_threshold) R = [r for r in R if r[0] in [b'car','bus']] #print('\t\t%d cars found' % len(R)) if len(R): WH = np.array(Iorig.shape[1::-1],dtype=float) Lcars = [] for i,r in enumerate(R): cx,cy,w,h = (old_div(np.array(r[2]),np.concatenate( (WH,WH) ))).tolist() tl = np.array([cx - w/2., cy - h/2.]) br = np.array([cx + w/2., cy + h/2.]) label = Label(0,tl,br) Icar = crop_region(Iorig,label) cv2.imwrite("crop1.png",Icar) Icar1 = cv2.imread("crop1.png") Lcars.append(label) return Lcars
def draw_car(img, Lcars, Tcars, Ccars, IDcars, Llps, lp_strs): print ('Performing outputting car ...') YELLOW = ( 0,255,255) RED = ( 0, 0,255) WHITE = (255,255,255) I = img if Lcars: for i,(lcar, tcar, ccar, idcar) in enumerate(zip(Lcars, Tcars, Ccars, IDcars)): draw_label(I,lcar,color=YELLOW,thickness=3) if (ccar is not np.nan): car_cat = str(tcar.decode("utf-8")) + " " + ccar + " " + str(idcar) else: car_cat = str(tcar.decode("utf-8")) + " " + str(idcar) draw_text(I,lcar,car_cat,color=YELLOW,thickness=1) lp_label = Llps[i] lp_label_str = lp_strs[i] if (lp_label is not np.nan): pts = lp_label.pts*lcar.wh().reshape(2,1) + lcar.tl().reshape(2,1) ptspx = pts*np.array(I.shape[1::-1],dtype=float).reshape(2,1) draw_losangle(I,ptspx,RED,3) if (lp_label_str is not np.nan): lp_str = lp_label_str.strip() llp = Label(0,tl=pts.min(1),br=pts.max(1)) write2img(I,llp,lp_str) sys.stdout.write('%s\n' % lp_str) else: if (lp_label_str is not np.nan): lp_str = lp_label_str.strip() draw_text2(I,lcar,lp_str,color=WHITE,thickness=3) sys.stdout.write('%s\n' % lp_str) return I
print('\t\t%d cars found' % len(R)) if len(R): Iorig = cv2.imread(img_path) WH = np.array(Iorig.shape[1::-1], dtype=float) Lcars = [] for i, r in enumerate(R): cx, cy, w, h = (np.array(r[2]) / np.concatenate( (WH, WH))).tolist() tl = np.array([cx - w / 2., cy - h / 2.]) br = np.array([cx + w / 2., cy + h / 2.]) label = Label(0, tl, br) Icar = crop_region(Iorig, label) Lcars.append(label) cv2.imwrite('%s/%s_%dcar.png' % (output_dir, bname, i), Icar) lwrite('%s/%s_cars.txt' % (output_dir, bname), Lcars) except: traceback.print_exc() sys.exit(1) sys.exit(0)
def getSquare(self): tl, br = self.pts.min(1), self.pts.max(1) return Label(-1, tl, br)
def __init__(self, cl, pts, prob): self.pts = pts tl = np.amin(pts, 1) br = np.amax(pts, 1) Label.__init__(self, cl, tl, br, prob)
sys.stdout.write('%s' % bname) if Lcar: for i, lcar in enumerate(Lcar): draw_label(I, lcar, color=YELLOW, thickness=3) lp_label = '%s/%s_%dcar_lp.txt' % (output_dir, bname, i) lp_label_str = '%s/%s_%dcar_lp_str.txt' % (output_dir, bname, i) if isfile(lp_label): Llp_shapes = readShapes(lp_label) pts = Llp_shapes[0].pts * lcar.wh().reshape( 2, 1) + lcar.tl().reshape(2, 1) ptspx = pts * np.array(I.shape[1::-1], dtype=float).reshape( 2, 1) draw_losangle(I, ptspx, RED, 3) if isfile(lp_label_str): with open(lp_label_str, 'r', encoding='utf-8') as f: lp_str = f.read().strip() llp = Label(0, tl=pts.min(1), br=pts.max(1)) I = write2img(I, llp, lp_str) sys.stdout.write(',%s' % lp_str) cv2.imwrite('%s/%s_output.png' % (output_dir, bname), I) sys.stdout.write('\n')
from src.display import Display from src.label import Label from src.save import Save from src.transform import Transform from sys import argv if len(argv) < 2: print('You must specify a name argument.') else: config = Config().get() capture = Capture(config) trans = Transform(config) display = Display() detect = Detect() label = Label() with capture, display: key = '' while key != 'q': success = False image = capture.frame() disk = trans.image_copy(image) disk = trans.image_color_flip(disk) small = trans.scale_image(image) locs = detect.locations(small) if len(locs) == 1: success = True loc = trans.scale_location(locs[0]) label.set_image(image).set_location(loc) image = label.outline().header(argv[1]).get_image()
print('\t\t%d vehicles found' % len(R)) if len(R): Iorig = cv2.imread(img_path) WH = np.array(Iorig.shape[1::-1], dtype=float) Lcars = [] for i, r in enumerate(R): cx, cy, w, h = (np.array(r[2]) / np.concatenate( (WH, WH))).tolist() tl = np.array([cx - w / 2., cy - h / 2.]) br = np.array([cx + w / 2., cy + h / 2.]) label = Label(0, tl, br, category=r[0].decode("utf-8")) Icar = crop_region(Iorig, label) Lcars.append(label) cv2.imwrite( # '%s/%s_%dcar.png' % (output_dir, bname, i), Icar) '%s/%s_car_%d.png' % (output_dir, bname, i), Icar) lwrite('%s/%s_cars.txt' % (output_dir, bname), Lcars, write_category_names=True) except: traceback.print_exc()