def process_top_dials(seg_threshold, min_area, max_area, thresh_angle, k, num_sample_points): global top_dials # Get a binary mask and clean it up. retval, mask = cv2.threshold(top_dials_gray, seg_threshold, 255, cv2.THRESH_BINARY_INV) median = cv2.medianBlur(mask, 21) mask = cv2.morphologyEx(median, cv2.MORPH_CLOSE, None, iterations=6) mask = cv2.morphologyEx(median, cv2.MORPH_OPEN, None, iterations=3) imshow(mask, "MASK") num_pixels = mask.size num_nonzero_pixels = cv2.countNonZero(mask) ratio = float(num_nonzero_pixels) / num_pixels print "Fraction of nonzero pixels:", ratio # Case 1: If ratio of nonzero pixels is too high, the threshold is too high. if ratio > 0.15: print " threshold is too high" return "high" # Find contours of the binary mask and sort them by area _, contours, _ = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) # Filter out the contours outside of the allowed area contours = [ cnt for cnt in contours if min_area <= cv2.contourArea(cnt) <= max_area ] contours.sort(key=cv2.contourArea, reverse=True) # Sort by area # Check if the remaining contours contain four good contours. angles = [] tmp = top_dials.copy() for i, cnt in enumerate(contours): angle = from_arrow_cnt_to_angle(tmp, cnt, thresh_angle, k, NUM_SAMPLE_POINTS_SMALL_ARROW) if angle == float('inf'): print "ARROW TIP NOT FOUND. Skipping this contour." imshow(tmp, "Arrow tip not found!") continue print "(searching ...) Angle {}: {}".format(i, "%.1f" % angle) angles.append((cnt, angle)) # Case 2: If four good contours have been found, threshold is sufficiently good => # => We can return four angles of the short arrows. if len(angles) == 4: # Return angles of arrows from left to right. angles.sort(key=lambda x: x[0][0][0][0]) top_dials = tmp return [angle for cnt, angle in angles] # Case 3: If four good contours haven't been found, threshold is too low. print " threshold is too low" return "low"
img2 = cv2.imread(filename) # Read a colored image h, w = img.shape #img = cv2.resize(img,(300, 300)) This is skewing the ratios #img2 = cv2.resize(img,(300, 300)) img = scaled_resize(img, 425) img2 = scaled_resize(img2, 425) # if h>600: # img = cv2.resize(img, (w/4, h/4)) # img2 = cv2.resize(img2, (w/4, h/4)) # else: # img = cv2.resize(img, (w/4, h/4)) # img2 = cv2.resize(img2, (w/4, h/4)) """ Find max contour and find points inside """ #def max_contours(img, img2:) """ Apply canny edge detection to image first """ #img = auto_canny(img) """ Use either contour detection or hough transform to identify colonies """ #circ2, img4 = process_image_using_canny(img, img2) #circ2, img4 = process_image_using_contours(img, img2) circ2, img4 = hough_circles(img, img2) #import pdb; pdb.set_trace() print len(circ2) #import pdb; pdb.set_trace() imshow(np.hstack([img4]), 'homi') #import pdb; pdb.set_trace()
import numpy as np import cv2 from matplotlib import pyplot as plt from helpers import imshow img = cv2.imread('images/img_true.jpg') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) # noise removal kernel = np.ones((3,3),np.uint8) opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2) imshow(opening, '') # sure background area sure_bg = cv2.dilate(opening,kernel,iterations=3) # Finding sure foreground area dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5) ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0) # Finding unknown region sure_fg = np.uint8(sure_fg) unknown = cv2.subtract(sure_bg,sure_fg) # Marker labelling ret, markers = cv2.connectedComponents(sure_fg) # Add one to all labels so that sure background is not 0, but 1 markers = markers+1
# CONSTANTS: K = 10 THRESH_ANGLE = 50 NUM_SAMPLE_POINTS_SMALL_ARROW = 50 NUM_SAMPLE_POINTS_LONG_ARROW = 250 SMALL_ARROW_MIN_AREA = 3000 SMALL_ARROW_MAX_AREA = 6000 # ============================================================================= # STEP 1: Get the Region of Interest (ROI) and Find Tilt Angle of the Meter # ============================================================================= print "*" * 30, "\nSTEP 1: LOOKING FOR THE METER ..." image = cv2.imread(IMG_PATH) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) imshow(gray) retval, mask = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY_INV) imshow(mask) _, contours, _ = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) contours = sorted(contours, key=cv2.contourArea, reverse=True) index = 1 # alternatively can use a range of reasonable areas cnt = contours[index] # Find Tilt Angle of the Meter rect = cv2.minAreaRect(cnt) box = cv2.boxPoints(rect) box = np.int0(box) image = cv2.drawContours(image, [box], 0, (0, 0, 255), 6) base_angle = get_angle([100, 0], box[0] - box[1]) print "Tilt (base) angle of the meter:", "%.1f" % base_angle
testing_dir = "/home/wingman2/datasets/personas/test/" # testing_dir = "/home/wingman2/code/Facial-Similarity-with-Siamese-Networks-in-Pytorch/data/faces/testing/" model = SiameseNetwork().cuda() model.load_state_dict(torch.load('/home/wingman2/models/siamese-faces-160.pt')) model.eval() data_transforms_test = transforms.Compose( [transforms.Resize((100, 100)), transforms.ToTensor()]) folder_dataset_test = ImageFolder(root=Config.testing_dir) siamese_dataset = SiameseNetworkDataset(imageFolderDataset=folder_dataset_test, transform=data_transforms_test, should_invert=False) test_dataloader = DataLoader(siamese_dataset, num_workers=8, batch_size=1, shuffle=True) dataiter = iter(test_dataloader) x0, _, _ = next(dataiter) for i in range(10): _, x1, label2 = next(dataiter) concatenated = torch.cat((x0, x1), 0) output1, output2 = model(Variable(x0).cuda(), Variable(x1).cuda()) euclidean_distance = F.pairwise_distance(output1, output2) imshow(torchvision.utils.make_grid(concatenated), 'Dissimilarity: {:.2f}'.format(euclidean_distance.item()))
# noise removal kernel = np.ones((3,3),np.uint8) opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2) # sure background area sure_bg = cv2.dilate(opening,kernel,iterations=3) # Finding sure foreground area dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5) ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0) # Finding unknown region sure_fg = np.uint8(sure_fg) unknown = cv2.subtract(sure_bg,sure_fg) # Marker labelling ret, markers = cv2.connectedComponents(sure_fg) # Add one to all labels so that sure background is not 0, but 1 markers = markers+1 # Now, mark the region of unknown with zero markers[unknown==255] = 0 markers = cv2.watershed(img,markers) #import pdb; pdb.set_trace() thresh[markers == -1] = 255 imshow(thresh, 'yoyo')
filename = args['image'] """ Read the input file and resize the image""" img = cv2.imread(filename, 0) # Reads a grayscale image img2 = cv2.imread(filename) # Read a colored image h, w = img.shape #img = cv2.resize(img,(300, 300)) This is skewing the ratios #img2 = cv2.resize(img,(300, 300)) img = scaled_resize(img, 425) img2 = scaled_resize(img2, 425) # if h>600: # img = cv2.resize(img, (w/4, h/4)) # img2 = cv2.resize(img2, (w/4, h/4)) # else: # img = cv2.resize(img, (w/4, h/4)) # img2 = cv2.resize(img2, (w/4, h/4)) """ Find max contour and find points inside """ #def max_contours(img, img2:) """ Apply canny edge detection to image first """ #img = auto_canny(img) """ Use either contour detection or hough transform to identify colonies """ #circ2, img4 = process_image_using_canny(img, img2) #circ2, img4 = process_image_using_contours(img, img2) circ2, img4 = hough_circles(img, img2) #import pdb; pdb.set_trace() print len(circ2) #import pdb; pdb.set_trace() imshow(np.hstack([img4]), 'homi') #import pdb; pdb.set_trace()
""" Build the argument parser """ ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Path to the image") args = vars(ap.parse_args()) filename = args['image'] """ Read the input file and resize the image""" img = cv2.imread(filename, 0) # Reads a grayscale image img2 = cv2.imread(filename) # Read a colored image img = cv2.resize(img,(300, 300)) img2 = cv2.resize(img,(300, 300)) """ Find max contour and find points inside """ #def max_contours(img, img2:) """ Apply canny edge detection to image first """ #img = auto_canny(img) """ Use either contour detection or hough transform to identify colonies """ circ2, img4 = process_image_using_canny(img, img2) #circ2, img4 = process_image_using_contours(img, img2) #scirc2, img4 = hough_circles(img, img2) #import pdb; pdb.set_trace() print len(circ2) #import pdb; pdb.set_trace() imshow(img4, 'homi') import pdb; pdb.set_trace()
if len(classes) == 1 and classes[0] == -1: classes = list(range(n_classes)) labels = torch.LongTensor([classes]) noise = torch.rand(1, 1, embed_dim) if cuda: G.load_state_dict(G_weights) G.cuda() labels = labels.cuda() noise = noise.cuda() else: G.load_state_dict(G_weights) images = G(labels[None], noise) for i in range(len(images)): imshow(images[i].detach().numpy()) plt.show() if not os.path.exists(outputs_path): os.mkdir(outputs_path) else: image_number = len(os.listdir(outputs_path)) save_image(images.data, os.path.join(outputs_path, "%d.png" % image_number), nrow=1, normalize=True)