def find_and_transform_board(image, sections, board_settings): if (board_settings["border_color"] == "RED"): mask1 = utils.threshold(image, "RED1") mask2 = utils.threshold(image, "RED2") contours = cv2.bitwise_or(mask1, mask2) else: contours = utils.threshold(image, board_settings["border_color"]) dilated = utils.dilate(contours) eroded = utils.erode(dilated) points = find_points(eroded) flood_mask = np.zeros((eroded.shape[0] + 2, eroded.shape[1] + 2), np.uint8) cv2.floodFill(eroded, flood_mask, (0, 0), 255) warped_image = transform_corners(image, points) warped_border = transform_corners(eroded, points) flood_mask = np.zeros( (warped_border.shape[0] + 2, warped_border.shape[1] + 2), np.uint8) cv2.floodFill(warped_border, flood_mask, (0, 0), 255) sections = find_sections(warped_image, warped_border, sections, board_settings) return warped_image, sections, points
def recognize_image(): img_data = re.sub(r'^data:image/.+;base64,', '', request.form['img']) img_bytes = base64.b64decode(img_data) img = Image.open(io.BytesIO(img_bytes)) img = img.split()[3] # remove alpha iarr = np.array(img) flat = iarr.flatten() threshold(flat) clf = joblib.load(os.path.join(CLASSIFIERS_DIR, 'svc.pkl')) results = clf.predict([flat]) prob = clf.predict_proba([flat])[0] print (results, clf.decision_function([flat])) print (prob, np.where(prob == prob.max()), type(np.where(prob == prob.max())[0][0])) # Render chart d = {'values': prob} df = pd.DataFrame(d) p = Bar(df, values='values', label='index', title="SVC predict_proba", legend=False, toolbar_location=None) plot_script, plot_div = components(p) return jsonify({'status': 'ok', 'svc': {'predicted': int(results[0]), 'prob': int(np.where(prob == prob.max())[0][0]), 'bokeh_js': plot_script, 'bokeh_div': plot_div} })
def find_board(image, board_settings): if (board_settings["border_color"] == "RED"): mask1 = utils.threshold(image, "RED1") mask2 = utils.threshold(image, "RED2") contours = cv2.bitwise_or(mask1, mask2) else: contours = utils.threshold(image, board_settings["border_color"]) dilated = utils.dilate(contours) eroded = utils.erode(dilated) points = find_points(eroded) return points is not None
def find_sections(image, border, sections, board_settings): thresholded = utils.threshold(image, board_settings["grid_color"]) dilated = utils.dilate(thresholded, iter_num=int(board_settings["dilation"])) eroded = utils.erode(dilated, iter_num=int(board_settings["erosion"])) black_sections = cv2.bitwise_or(eroded, border) white_sections = cv2.bitwise_not(black_sections) im, contours, hierarchy = cv2.findContours(white_sections.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) contours = sorted(contours, key=cv2.contourArea, reverse=True) for i in range(len(contours)): if cv2.contourArea(contours[i]) * int(board_settings[ "min_section_scale"]) > image.shape[0] * image.shape[1]: section_num = i + 1 cimg = np.zeros_like(white_sections) cv2.drawContours(cimg, contours, i, color=255, thickness=-1) rect = cv2.boundingRect(contours[i]) sections[str(section_num)] = Section(cimg, str(section_num), rect) else: break return sections
def lat(coord, frame): from utils import threshold import numpy as np lat = frame[coord[1]:coord[-1], coord[0]:coord[-2]] t = threshold(np.asarray(image)[34:45, 50:222]) n = np.where(t == True) y = sum(n[1]) / len(n[1]) return (y / 160 * 20) - 10
def LAT_6(coord, frame): lat = frame[coord[1]:coord[-1], coord[0]:coord[-2]] lat = cv2.cvtColor(lat, cv2.COLOR_RGB2GRAY) # print(lat.shape) t = threshold(np.asarray(lat)[34:45, 50:222]) n = np.where(t == True) y = sum(n[1])/len(n[1]) return (y/160 * 20) - 10
def plot_images(dataset, patient_id, data_arr, gt_arr, pred_arr, output_dir, bbox_flag, bbox_metrics, dice): """ Plots 15 different views of a given patient imaging data. # bbox metrics from distance calculation Args: dataset (str): Name of dataset. patient_id (str): Unique patient id. path_to_data (str): Path to nrrd file containing the image. path_to_mask_list (list) List of strings paths to nrrd files containing contours. Files must be in named following the naming convention. At least one mask(contour) should be provided as this is used to set the viewing bounds ofthe image. If multiple masks are provided, they are added up and the resultis used to set the bounds. Make sure to pass the masks in the same order(for each patient) so that the contour colors do not flip on you. output_dir (str): Path to folder where the png will be saved bbox_flag (bool): Boolean whether to show bounding box or not. If True, it will be set based on the viewing bounds. Returns: None Raises: Exception if an error occurs. """ if not os.path.exists(output_dir): os.makedirs(output_dir) try: gt_bbox_metrics = bbox_metrics["ground_truth_bbox_metrics"] pred_bbox_metrics = bbox_metrics["prediction_bbox_metrics"] pred_arr = utils.threshold(pred_arr) mask_arr_list = [gt_arr, pred_arr] mask_list_names = ["gt", "pred"] # bbox and centroid will be calculated based on gt_arr only # combined = utils.combine_masks(mask_arr_list) gt_bbox = utils.get_bbox(gt_arr) pred_bbox = utils.get_bbox(pred_arr) # decided to use geometric center as opposed to center of mass to show the actual center of the bounding box - although still called com, it is the geometric center # com = ndimage.measurements.center_of_mass(combined) # print(com) # com = getClosestSlice(com) # print(com) com_gt = getClosestSlice( (gt_bbox_metrics["Z"]["center"], gt_bbox_metrics["Y"]["center"], gt_bbox_metrics["X"]["center"])) com_pred = getClosestSlice((pred_bbox_metrics["Z"]["center"], pred_bbox_metrics["Y"]["center"], pred_bbox_metrics["X"]["center"])) assert gt_bbox_metrics["Z"]["min"] == gt_bbox[0], "bbox calc incorrect" assert gt_bbox_metrics["Z"]["max"] == gt_bbox[1], "bbox calc incorrect" assert gt_bbox_metrics["Y"]["min"] == gt_bbox[2], "bbox calc incorrect" assert gt_bbox_metrics["Y"]["max"] == gt_bbox[3], "bbox calc incorrect" assert gt_bbox_metrics["X"]["min"] == gt_bbox[4], "bbox calc incorrect" assert gt_bbox_metrics["X"]["max"] == gt_bbox[5], "bbox calc incorrect" # plot plot_figure(dataset, patient_id, data_arr, mask_arr_list, mask_list_names, com_gt, com_pred, [gt_bbox, pred_bbox], bbox_flag, output_dir, bbox_metrics["distance"], dice) print("{}_{} saved".format(dataset, patient_id)) except Exception as e: print("Error in {}_{}, {}".format(dataset, patient_id, e))
def prep_model(): """ Build and train models and save them for future use. """ mndata = MNIST('data') images, labels = mndata.load_training() images = images[:2000] labels = labels[:2000] train_images, test_images, train_labels, test_labels = train_test_split(images, labels, train_size=0.8, random_state=0) for image in chain(train_images, test_images): threshold(image) clf = svm.SVC(probability=True) clf.fit(train_images, train_labels) print(clf.score(test_images, test_labels)) if not os.path.exists(CLASSIFIERS_DIR): os.makedirs(CLASSIFIERS_DIR) joblib.dump(clf, os.path.join(CLASSIFIERS_DIR, 'svc.pkl')) print(sklearn.__version__)
def AirSpeed_3(coord, frame): x1, y1, x2, y2 = coord frame = frame[y1:y2, x1:x2] # print("threshold shape", frame.shape) frame = frame[155:195, 5:50] frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) frame = utils.threshold(frame).astype('float') # plt.imshow(frame, cmap=plt.cm.gray) txt = pytesseract.image_to_string(frame) txt = txt.replace("D","0").replace("U", "0").replace("O","0").replace("S", "5") return txt
def preprocess(self, images, masks): # images = threshold(images, np.min(images), np.max(images)) images = threshold(images, -100, 400) # images = norm_images(images) # images = equalizeHist(images) # images = threshold(images, np.min(images), np.max(images)) # print((np.min(masks), np.max(masks))) masks[masks < 2] = 0 masks /= 2 # print((np.min(masks), np.max(masks))) # assert np.sum(masks[masks>0]) == np.sum(masks>0) return images, masks
def __init__(self): print("****** Start CV Part ******") img = utils.readImage(str(input("Please Input the ImgPath: "))) img_ = img.copy() # back-up; img = utils.shift_demo(img, 10, 50) img = self.colorFilter(img, img_) img = utils.threshold(img) img1 = img_.copy() region = self.roi_solve(img) for i in range(len(region)): rect2 = region[i] w1, w2 = rect2[0], rect2[0] + rect2[2] h1, h2 = rect2[1], rect2[1] + rect2[3] box = [[w1, h2], [w1, h1], [w2, h1], [w2, h2]] cv2.drawContours(img1, np.array([box]), 0, (0, 0, 255), 1) # self.saveImage(img_, box, i) utils.showImage(img1, "Result")
def pipeline(img_name): path = f'./static/uploaded_images/{img_name}.jpeg' try: img = Image.open(path) except: return ValueError # preprocessing image img = rescale_image(img) thresh = threshold(img) cnts, bbox = find_bbox(thresh) img = crop_img(img, bbox) final_img = remove_noise_and_smooth(img) # finding text in image text = pytesseract.image_to_string(final_img) # searching for dates date = find_date(text) if date is None: return date return date.strftime("%Y-%m-%d")
def saveImage(self, img_, box, index): current_path = os.path.abspath(__file__) # 获取当前文件的父目录 path = os.path.abspath( os.path.dirname(current_path) + os.path.sep + ".") + "\\result" if not os.path.exists(path): os.makedirs(path) savepath = path + "\\" + str(datetime.datetime.now().strftime( "%Y%m%d%H%M%S")) + "-" + str(index) + ".png" Xs = [i[0] for i in box] Ys = [i[1] for i in box] x1 = min(Xs) x2 = max(Xs) y1 = min(Ys) y2 = max(Ys) hight = y2 - y1 width = x2 - x1 img_ = utils.shift_demo(img_, 10, 50) img_ = utils.threshold(img_) crop_img = img_[y1:y1 + hight, x1:x1 + width] crop_img = 255 - crop_img cv2.imwrite(savepath, crop_img) request.callApi(savepath) request.ocr(crop_img, "test1")
if __name__ == '__main__': # start the capture stdscr = curses.initscr() curses.noecho() curses.cbreak() cap = cv2.VideoCapture(0) cv2.namedWindow("test") cv2.createTrackbar("level", "test", 150, 255, nope) cv2.createTrackbar("inv", "test", 0, 1, nope) while(1): (un,src) = cap.read() rects = gen_grid(src) r = cv2.getTrackbarPos("level","test") if cv2.getTrackbarPos("inv", "test") == 1: mask = threshold(src, r, False) else: mask = threshold(src, r) points = get_points(mask) rows = {i:[] for i in range(8)} for p in points: (i,j) = get_grid_cell(src, p) cv2.circle(mask, (p[1],p[0]), 10, (100,100,100,200)) cv2.circle(mask, (p[1],p[0]), 5, (100,100,100,200)) rows[i].append(j) print_dic(rows) stdscr.refresh() draw_grid(mask,rects) cv2.imshow("test", mask) cv2.waitKey(1)
def __getitem__(self, item): batch_size = self.batch_size image_size = self.image_size item = item % self.steps_per_epoch num_slices = self.nums_slice num_slices_cum = np.cumsum(num_slices) image_batch, mask_batch = None, None s = item * batch_size e = (item + 1) * batch_size s_index = np.searchsorted(num_slices_cum, s) e_index = np.searchsorted(num_slices_cum, e) if s_index < len(num_slices) and e_index < len(num_slices): # print('{0} in {1}'.format(s, s_index)) # print('{0} in {1}'.format(e, e_index)) if s_index == e_index: images, masks = self.read_case(self.images_file_train[s_index], self.masks_file_train[s_index]) if s_index == 0: slice_index = s else: slice_index = s - num_slices_cum[s_index - 1] image_batch = images[slice_index:slice_index + batch_size] mask_batch = masks[slice_index:slice_index + batch_size] else: images_s, masks_s = self.read_case( self.images_file_train[s_index], self.masks_file_train[s_index]) images_e, masks_e = self.read_case( self.images_file_train[e_index], self.masks_file_train[e_index]) image_batch = VolumnGenerator.__get_image_batch( images_s, s, num_slices_cum, s_index, images_e, e, e_index) mask_batch = VolumnGenerator.__get_image_batch( masks_s, s, num_slices_cum, s_index, masks_e, e, e_index) # print('batch_index = {0} from {1} to {2} in volumn index {3} and {4}, batch_size = {5}'. # format(item, s, e, s_index, e_index, image_batch.shape)) elif item * batch_size < num_slices_cum[-1]: images, masks = self.read_case(self.images_file_train[s_index], self.masks_file_train[s_index]) rem_s = num_slices[-1] + item * batch_size - num_slices_cum[-1] image_batch = images[rem_s:] mask_batch = masks[rem_s:] # print('batch_index = {0} from {1} to {2} in volumn index {3} and {4}, batch_size = {5}'. # format(item, s, num_slices_cum[-1], s_index, s_index, image_batch.shape)) if image_batch is not None: image_batch = np.swapaxes(image_batch, 1, 3) mask_batch = np.swapaxes(mask_batch, 1, 3) if image_size is not None: image_batch = np.array( [cv2.resize(image, image_size) for image in image_batch]) mask_batch = np.array( [cv2.resize(image, image_size) for image in mask_batch]) dims = image_batch.shape image_batch, mask_batch = image_batch.reshape( dims + (1, )), mask_batch.reshape(dims + (1, )) image_batch = threshold(image_batch, self.min_value, self.max_value) if self.typename == 'liver': mask_batch[mask_batch > 0] = 1 return image_batch, mask_batch
# if patient_id != "1530-TC330" or patient_id != "15-TC027": try: print(patient_id) Z = int(roi_image.split("_")[7]) Y = int(roi_image.split("_")[8]) X = int(roi_image.split("_")[9].split(".")[0]) # image_obj = sitk.ReadImage(os.path.join(_from, roi_image)) image_arr = sitk.GetArrayFromImage(image_obj) print(image_obj.GetSpacing(), image_arr.shape) # size should match model # interpolate image_arr = np.interp(image_arr, [-1024, 3071], [0, 1]) label_prediction = np.squeeze( original_model.predict(image_arr.reshape(1, 1, *image_arr.shape))) label_prediction = threshold(label_prediction) ############### if label_prediction[label_prediction == 1].sum() > 0: # get image_interpolated and label_interpolated path_to_image = "{}/{}/{}/{}_{}_{}".format( MASTER_FOLDER, dataset, "3_image_interpolated", dataset, patient_id, "image_interpolated_raw_raw_xx.nrrd") image_obj_org = sitk.ReadImage(path_to_image) image_arr_org = sitk.GetArrayFromImage( sitk.ReadImage(path_to_image)) print(image_arr_org.shape) # path_to_label = "{}/{}/{}/{}_{}_{}".format( MASTER_FOLDER, dataset, "4_label_interpolated", dataset,
def VTA_2(coord, frame): img = frame[coord[1]:coord[-1], coord[0]:coord[-2]] img = threshold(img) return np.count_nonzero(img)/(img.shape[0]*img.shape[1]) >= 0.1
y, x, h, w = cc['bbox'] for i in range(y, y + h): image[i, x] = box_rgb_color image[i, x + w] = box_rgb_color for j in range(x, x + w): image[y, j] = box_rgb_color image[y + h, j] = box_rgb_color return image if __name__ == '__main__': if len(sys.argv) != 2: raise SyntaxError('usage: yellow_circles.py [path to image]') input_image = imread(sys.argv[1]) yellow = get_yellow(input_image) yellow_binary = threshold(yellow, get_threshold_otsu(yellow)) imsave( 'yellow_binary.png', np.interp(yellow_binary, (yellow_binary.min(), yellow_binary.max()), (0, 255)).astype(np.uint8)) yellow_ccs = get_ccomponents(yellow_binary) yellow_ccs = remove_small_components(yellow_ccs, 50) with open('yellow_ccs.txt', 'w') as f: for cc in yellow_ccs: write_cc(cc, f) yellow_ccs = [add_error_to_circle(cc) for cc in yellow_ccs] yellow_circle_ccs = filter_by_error(yellow_ccs, 0.1) image_with_boxes = draw_all_lbbs(input_image, yellow_circle_ccs, (255, 0, 0)) imsave('output.png', image_with_boxes) plt.imshow(image_with_boxes)
# sys.setrecursionlimit(1500) # Read img_ gray format img_path = 'data/8.tif' img_gray = utils.incise(img_path) # smooth the img img_smooth = utils.dilation_erosion(img_gray) # Extract partitions partitions, num_par = utils.partition(img_smooth) # clean some partitions clean_img = [] for i in partitions: if utils.threshold(i, 100): clean_img.append(i) # TODO: this part can add one incise the dna # get the thinning img thinning_image = [] for i in clean_img: print('thinning.......') thinning_image.append(utils.thinning(i)) # count the head and get stat summary stat_list = [] for i in thinning_image: stat, heads = utils.head_and_len(i) stat_list.append(stat)
# Save estimated map to disk os.makedirs(os.path.join(args.out, 'intermediate', 'estimated_map'), exist_ok=True) cv2.imwrite(os.path.join(args.out, 'intermediate', 'estimated_map', dictionaries[0]['filename']), orig_img_w_heatmap_origsize.transpose((1, 2, 0))[:, :, ::-1]) # Tensor -> int est_count_int = int(round(est_count.item())) # The estimated map must be thresholded to obtain estimated points for t, tau in enumerate(args.taus): if tau != -2: mask, _ = utils.threshold(est_map_np_origsize, tau) else: mask, _, mix = utils.threshold(est_map_np_origsize, tau) bmm_tracker.feed(mix) centroids_wrt_orig = utils.cluster(mask, est_count_int, max_mask_pts=args.max_mask_pts) # Save thresholded map to disk os.makedirs(os.path.join(args.out, 'intermediate', 'estimated_map_thresholded', f'tau={round(tau, 4)}'), exist_ok=True) cv2.imwrite(os.path.join(args.out, 'intermediate', 'estimated_map_thresholded',
for patient in data: #### VARIABLES patient_id = patient["patient_id"] dataset = patient["dataset"] # formatted (cropped & reshaped) if MULTI_PREDICTION = False # not cropped or reshaped if MULTI_PREDICTION = True image = patient["image"] # original size image_sitk_obj = patient["image_sitk_obj"] label_sitk_obj = patient["label_sitk_obj"] spacing = get_spacing(image_sitk_obj) #### PREDICT if MULTI_PREDICTION: label_prediction = multi_prediction(image, original_model, IMAGE_SHAPE) label_prediction = threshold(np.squeeze(label_prediction), 4.5) else: label_prediction = original_model.predict( image.reshape(1, *image.shape)) label_prediction = threshold(np.squeeze(label_prediction)) # 0.5 # if there are voxels predicted: if label_prediction[label_prediction == 1].sum() > 0: # save model output as nrrd # this will pad the prediction to match the size of the originals # for localization, 80, 96, 96 => 84, 108, 108 # for segmentation, 64, 160, 160 => 76, 196, 196 pred_sitk_obj = generate_sitk_obj_from_npy_array( image_sitk_obj, label_prediction, True, os.path.join(dir_name,
sum_term1 += term1.item() sum_term2 += term2.item() sum_term3 += term3.item() sum_loss += term1 + term2 + term3 # Update progress bar loss_avg_this_epoch = sum_loss.item() / (batch_idx + 1) iter_val.set_postfix( avg_val_loss_this_epoch=f'{loss_avg_this_epoch:.1f}-----') # The estimated map must be thresholed to obtain estimated points # BMM thresholding est_map_numpy = est_maps[0, :, :].to(device_cpu).numpy() est_map_numpy_origsize = skimage.transform.resize( est_map_numpy, output_shape=orig_shape, mode='constant') mask, _ = utils.threshold(est_map_numpy_origsize, tau=-1) # Obtain centroids of the mask centroids_wrt_orig = utils.cluster(mask, est_count_int, max_mask_pts=args.max_mask_pts) # Validation metrics target_locations_wrt_orig = normalzr.unnormalize( target_locations_np, orig_img_size=target_orig_size_np) judge.feed_points(centroids_wrt_orig, target_locations_wrt_orig, max_ahd=loss_loc.max_dist) judge.feed_count(est_count_int, target_count_int) if time.time() > tic_val + args.log_interval: tic_val = time.time()
def preprocess(self, images, masks): images = threshold(images, -100, 400) # images = norm_images(images) masks[masks > 0] = 1 return images, masks
def pipeline(img, line, M, Minv, cameraMat, distCoeffs): img_size = (img.shape[1], img.shape[0]) width, height = img_size img = cv2.undistort(np.copy(img), cameraMat, distCoeffs) binary_warped = cv2.warpPerspective(threshold(img, mag_dir_thresh=False), M, (width, height)) out_img = np.dstack((binary_warped, binary_warped, binary_warped)) * 255 margin = 80 minpix = 50 nwindows = 9 window_height = np.int(binary_warped.shape[0] / nwindows) if not line.first_frame_processed: # Assuming you have created a warped binary image called "binary_warped" # Take a histogram of the bottom half of the image histogram = np.sum(binary_warped[binary_warped.shape[0] // 2:, :], axis=0) # Create an output image to draw on and visualize the result #out_img = np.uint8(np.dstack((binary_warped, binary_warped, binary_warped))*255) midpoint = np.int(histogram.shape[0] / 2) leftx_base = np.argmax(histogram[:midpoint]) rightx_base = np.argmax(histogram[midpoint:]) + midpoint nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) leftx_current = leftx_base rightx_current = rightx_base # Create empty lists to receive left and right lane pixel indices left_lane_inds = [] right_lane_inds = [] # Step through the windows one by one for window in range(nwindows): win_y_low = binary_warped.shape[0] - (window + 1) * window_height win_y_high = binary_warped.shape[0] - window * window_height win_xleft_low = leftx_current - margin win_xleft_high = leftx_current + margin win_xright_low = rightx_current - margin win_xright_high = rightx_current + margin #cv2.rectangle(out_img,(win_xleft_low,win_y_low),(win_xleft_high,win_y_high),(0,255,0), 3) #cv2.rectangle(out_img,(win_xright_low,win_y_low),(win_xright_high,win_y_high),(0,255,0), 3) good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0] good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0] left_lane_inds.append(good_left_inds) right_lane_inds.append(good_right_inds) if len(good_left_inds) > minpix: leftx_current = np.int(np.mean(nonzerox[good_left_inds])) if len(good_right_inds) > minpix: rightx_current = np.int(np.mean(nonzerox[good_right_inds])) # Concatenate the arrays of indices left_lane_inds = np.concatenate(left_lane_inds) right_lane_inds = np.concatenate(right_lane_inds) # Extract left and right line pixel positions leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] rightx = nonzerox[right_lane_inds] righty = nonzeroy[right_lane_inds] # Fit a second order polynomial to each left_fit = np.polyfit(lefty, leftx, 2) right_fit = np.polyfit(righty, rightx, 2) # Update current fit to Line line.update_fits(left_fit, right_fit) line.first_frame_processed = True else: nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) left_fit = line.avg_left_fit_coeffs right_fit = line.avg_right_fit_coeffs left_lane_inds = ( (nonzerox > (left_fit[0] * (nonzeroy**2) + left_fit[1] * nonzeroy + left_fit[2] - margin)) & (nonzerox < (left_fit[0] * (nonzeroy**2) + left_fit[1] * nonzeroy + left_fit[2] + margin))) right_lane_inds = ( (nonzerox > (right_fit[0] * (nonzeroy**2) + right_fit[1] * nonzeroy + right_fit[2] - margin)) & (nonzerox < (right_fit[0] * (nonzeroy**2) + right_fit[1] * nonzeroy + right_fit[2] + margin)) ) # Again, extract left and right line pixel positions leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] rightx = nonzerox[right_lane_inds] righty = nonzeroy[right_lane_inds] # Fit a second order polynomial to each left_fit = np.polyfit(lefty, leftx, 2) right_fit = np.polyfit(righty, rightx, 2) # Update current fit to Line line.update_fits(left_fit, right_fit) # Generate x and y values for plotting ploty = np.linspace(0, binary_warped.shape[0] - 1, binary_warped.shape[0]) left_fitx = left_fit[0] * ploty**2 + left_fit[1] * ploty + left_fit[2] right_fitx = right_fit[0] * ploty**2 + right_fit[1] * ploty + right_fit[2] warp_zero = np.zeros_like(binary_warped).astype(np.uint8) color_warp = np.dstack((warp_zero, warp_zero, warp_zero)) # Recast the x and y points into usable format for cv2.fillPoly() pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))]) pts_right = np.array( [np.flipud(np.transpose(np.vstack([right_fitx, ploty])))]) pts = np.hstack((pts_left, pts_right)) # Draw the lane onto the warped blank image cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0)) cv2.polylines(color_warp, np.int32([pts_left]), isClosed=False, color=(0, 0, 255), thickness=10) cv2.polylines(color_warp, np.int32([pts_right]), isClosed=False, color=(0, 0, 255), thickness=10) newwarp = cv2.warpPerspective(color_warp, Minv, (img.shape[1], img.shape[0])) # Combine the result with the original image result = cv2.addWeighted(img, 1, newwarp, 0.3, 0) ## Add Radius of Curvature text = 'Radius of Curve: ' + '{:04.3f}'.format(line.curvature) + 'm' cv2.putText(result, text, (30, 70), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 255, 255), 2) ## Add distance from center position_from_center = line.get_position_from_center() if position_from_center < 0: direction = 'Left' else: direction = 'Right' text = direction + ' side' + ' from center: ' + '{:04.3f}'.format( abs(position_from_center)) + 'm ' cv2.putText(result, text, (30, 120), cv2.FONT_HERSHEY_SIMPLEX, 1.5, (255, 255, 255), 2) return result
def preprocess(self, images, masks): images = threshold(images, np.min(images), np.max(images)) return images, masks
DARKNET_WEIGHTS_PATH = '/home/diendl/yolo_weights/yolov3-tiny.weights' IMAGE_DIR = '' LABELMAP = 'cfg/coco.names' graph = tf.Graph() with graph.as_default(): inputs = tf.placeholder( dtype=tf.float32, name='input_images', shape=[model.BATCH, model.WIDTH, model.HEIGHT, model.CHANNELS]) weights_list, predictions = model.forward(inputs) load_weights_ops = utils.load_darknet_weights(DARKNET_WEIGHTS_PATH, weights_list) thresholded = utils.threshold(detections=predictions, object_confidence_threshold=0.25) with tf.Session(graph=graph) as sess: tf.logging.set_verbosity(tf.logging.INFO) tf.logging.info('Loading weights from Darknet weights file...') sess.run(load_weights_ops) classes = utils.load_classes(LABELMAP) image1 = cv2.imread('dog-cycle-car.png') image2 = cv2.imread('scream.jpg') resized_image1 = utils.resize_image(image1, model.WIDTH) resized_image2 = utils.resize_image(image2, model.WIDTH) resized_image1 = np.expand_dims(resized_image1, 0) resized_image2 = np.expand_dims(resized_image2, 0)
import matplotlib.pyplot as plt import pai_io import skimage.morphology as morph import utils if __name__ == '__main__': #filename ='../images/gray/lenna_gray_noisy.png' filename = '/home/jsaavedr/Pictures/sketch.png' image = pai_io.imread(filename, as_gray=True) th = 150 bin = 1 - utils.threshold(image, th) bin = 1 - morph.binary_dilation(bin, morph.disk(3)) fig, ax = plt.subplots(1, 3) ax[0].imshow(image, cmap='gray') ax[0].set_title('image') ax[1].imshow(bin * 255, cmap='gray', vmin=0, vmax=255) ax[1].set_title('image_p') for i in range(3): ax[i].set_axis_off() plt.show()
''' Created on Aug 7, 2019 @author: jsaavedr ''' import utils import pai_io import bw import skimage.measure as measure import matplotlib.pyplot as plt if __name__ == '__main__': filename = '../images/gray/ten_coins.png' image = pai_io.imread(filename, as_gray=True) th_otsu = utils.get_threshold_otsu(image) bin_image = utils.threshold(image, th_otsu) print(bin_image.shape) label, num = measure.label(bin_image, return_num=True) fig, xs = plt.subplots(1, 3) xs[0].imshow(image, cmap='gray') xs[0].set_title('Image') xs[1].imshow(bin_image, cmap='gray') xs[1].set_title('Binary') xs[2].imshow(label, cmap='jet') xs[2].set_title('Labels nc : {}'.format(num)) for i in range(3): xs[i].set_axis_off() plt.show() #cc = bw.getCC(bin_image) #print(len(cc))
nib.save(segmented_nii_obj, segmented_filename) utils.write_dice_scores(filename_t1, cur_vol_dice, cur_slices_dice, DICE_METRICS_FILE) mean_dice += cur_vol_dice pred_vols.append(cur_vol) gt_vols.append(cur_vol_gt) # Reorient back to original before comparisons # print("Reorienting...") # utils.reorient(filename, DATA_DIR, SEG_DIR) # get probability volumes and threshold image print("Thresholding...") utils.threshold(filename_t1, SEG_DIR, SEG_DIR, thresh) mean_dice = mean_dice / len(filenames_t1) pred_vols = np.array(pred_vols) gt_vols = np.array(gt_vols) corr = np.corrcoef(pred_vols, gt_vols)[0, 1] print("*** Segmentation complete. ***") print("Mean DICE: {:.3f}".format(mean_dice)) print("Volume Correlation: {:.3f}".format(corr)) # save these two numbers to file metrics_path = os.path.join(STATS_DIR, "metrics.txt") with open(metrics_path, 'w') as f: f.write("Dice: {:.4f}\nVolume Correlation: {:.4f}\n".format( mean_dice, corr))
Filtro Mediana ''' import matplotlib.pyplot as plt import pai_io import skimage.morphology as morph import utils if __name__ == '__main__': #filename ='../images/gray/lenna_gray_noisy.png' filename = '../images/gray/rice.jpg' image = pai_io.imread(filename, as_gray=True) image_opening = morph.opening(image, morph.disk(31)) image_processed = image - image_opening th = utils.get_threshold_otsu(image_processed) bin = utils.threshold(image_processed, th) bin = morph.binary_opening(bin, morph.disk(11)) ig, ax = plt.subplots(1, 3) ax[0].imshow(image, cmap='gray') ax[0].set_title('image') ax[1].imshow(image_processed, cmap='gray', vmin=0, vmax=255) ax[1].set_title('image_p') ax[2].imshow(bin * 255, cmap='gray', vmin=0, vmax=255) ax[2].set_title('bin') for i in range(3): ax[i].set_axis_off() plt.show() # A = np.array([[0,0,0,0,0], # [0,1,1,1,0], # [0,1,1,1,0], # [0,1,1,1,0],
sy_kernel = [[1, 2, 1], [0, 0, 0], [-1, -2, -1]] # High pass filter conv_start = time.time() high = conv(image, high_pass_kernel) conv_end = time.time() print("Highpass execution time (s): " + str(conv_end - conv_start)) # Low pass filter low = conv(image, avg_kernel) low2 = conv(low, avg_kernel) low3 = conv(low2, avg_kernel) # Sobel edge filter sx = np.abs(conv(image, sx_kernel)) sx = threshold(sx, 0.3) sy = np.abs(conv(image, sy_kernel)) sy = threshold(sy, 0.3) sobel = sx + sy sobel[sobel > 255] = 255 if EXPORT_IMAGES: cv2.imwrite("../figures/part1/high_pup.jpg", high * 255) cv2.imwrite("../figures/part1/low_pup.jpg", low * 255) cv2.imwrite("../figures/part1/low2_pup.jpg", low2 * 255) cv2.imwrite("../figures/part1/low3_pup.jpg", low3 * 255) cv2.imwrite("../figures/part1/edgex_pup.jpg", sx * 255) cv2.imwrite("../figures/part1/edgey_pup.jpg", sy * 255) cv2.imwrite("../figures/part1/edge_pup.jpg", sobel * 255)