def test_hough_line_bad_input(): img = np.zeros(100) img[10] = 1 # Expected error, img must be 2D with testing.raises(ValueError): transform.hough_line(img, np.linspace(0, 360, 10))
def compareImages(): image1 = Image.open("../Images/image5.png") image2 = Image.open("../Images/image5_bold.png") blurredImage1 = image1.filter(ImageFilter.GaussianBlur(radius = 2)) imageData1 = toMatrix(blurredImage1, blurredImage1.size[1], blurredImage1.size[0]) blurredImage2 = image2.filter(ImageFilter.GaussianBlur(radius = 2)) imageData2 = toMatrix(blurredImage2, blurredImage2.size[1], blurredImage2.size[0]) h1, theta1, d1 = hough_line(imageData1) h2, theta2, d2 = hough_line(imageData2)
def houghLine(img2d): "gray input" med_filter = ndimg.median_filter(img2d, size = (5,5)) edges = filter.sobel(med_filter/255.) [H,theta,distances] = transform.hough_line(edges); imgsize = float(len(theta)*len(distances)) return H.sum()/imgsize
def calculate_rotation(image): # sometimes we snag corners, by cropping the left and right 10% of the image we focus only on the # vertical bars formed by the structure height, width = image.shape crop = int(width * 0.1) cropped_image = image[:, crop: width - crop] # Find edges that have a strong vertical direction vertical_edges = sobel_v(cropped_image) # Separate out the areas where there is a large amount of vertically-oriented stuff segmentation = segment_edge_areas(vertical_edges) # Draw a line that follows the center of the segments at each point, which should be roughly vertical # We should expect this to give us four approximately-vertical lines, possibly with many gaps in # each line skeletons = skeletonize(segmentation) # Use the Hough transform to get the closest lines that approximate those four lines hough = transform.hough_line(skeletons, np.arange(-constants.FIFTEEN_DEGREES_IN_RADIANS, constants.FIFTEEN_DEGREES_IN_RADIANS, 0.0001)) # Create a list of the angles (in radians) of all of the lines the Hough transform produced, with 0.0 # being completely vertical # These angles correspond to the angles of the four sides of the channels, which we need to # correct for angles = [angle for _, angle, dist in zip(*transform.hough_line_peaks(*hough))] if not angles: raise ValueError("Image rotation could not be calculated. Check the images to see if they're weird.") else: # Get the average angle and convert it to degrees offset = sum(angles) / len(angles) * 180.0 / math.pi if offset > constants.ACCEPTABLE_SKEW_THRESHOLD: log.warn("Image is heavily skewed. Check that the images are valid.") return offset
def rotate_pic(pic): """ rotate_pic finds the offset angle by measuring the grid with a Hough line transform. It then de-rotates by this amount """ # for speed, only look at a 500x500 slice in the center of the image centercut = np.copy( pic[int(pic.shape[0] / 2.) - 500:int(pic.shape[0] / 2.) + 500, int(pic.shape[1] / 2.) - 500:int(pic.shape[1] / 2.) + 500, 0]) # find the grid in the image by looking for brighter regions centermask = (centercut < 1) * (centercut > 0.8) h, theta, d = tf.hough_line(centermask, theta=np.linspace(np.pi / 2 - 0.2, np.pi / 2 + 0.2, 1000)) _, angles, dist = tf.hough_line_peaks(h, theta, d) # plt.figure() # plt.imshow(centermask) # for ii in range(len(angles)): # rho = dist[ii] # theta = angles[ii] # # y0 = (rho - 0 * np.cos(theta)) / np.sin(theta) # y1 = (rho - centermask.shape[1] * np.cos(theta)) / np.sin(theta) # # plt.plot([0,centermask.shape[0]],[y0,y1],'r-') angle = np.mean(angles * 180 / np.pi - 90) corrected_pic = tf.rotate(pic, angle, cval=1) return corrected_pic, angle
def show_hough_transform(image): h, theta, d = hough_line(canny(image)) fig, ax = plt.subplots(1, 3, figsize=(15, 6)) ax[0].imshow(image, cmap=cm.gray) ax[0].set_title('Input image') ax[0].set_axis_off() ax[1].imshow( np.log(1 + h), extent=[np.rad2deg(theta[-1]), np.rad2deg(theta[0]), d[-1], d[0]], cmap='gray', aspect=1 / 20) ax[1].set_title('Hough transform') ax[1].set_xlabel('Angles (degrees)') ax[1].set_ylabel('Distance (pixels)') ax[2].imshow(image, cmap=cm.gray) for _, angle, dist in zip(*hough_line_peaks(h, theta, d)): y0 = (dist - 0 * np.cos(angle)) / np.sin(angle) y1 = (dist - image.shape[1] * np.cos(angle)) / np.sin(angle) ax[2].plot((0, image.shape[1]), (y0, y1), '-r') ax[2].set_xlim((0, image.shape[1])) ax[2].set_ylim((image.shape[0], 0)) ax[2].set_axis_off() ax[2].set_title('Detected lines') plt.tight_layout() return hough_line_peaks(h, theta, d)
def hough_detect(binary_maps, vote_thresh=12): """ Use the Hough detection method to detect lines in the data. With enough lines, you can fill in the wave front.""" detection = [] print("Performing hough transform on binary maps...") for img in binary_maps: # Perform the hough transform on each of the difference maps transform, theta, d = hough_line(img.data) # Filter the hough transform results and find the best lines in the # data. Keep detections that exceed the Hough vote threshold. indices = (transform>vote_thresh).nonzero() distances = d[indices[0]] theta = theta[indices[1]] # Perform the inverse transform to get a series of rectangular # images that show where the wavefront is. # Create a map which is the same as the invTransform = sunpy.map.Map(np.zeros(img.data.shape), img.meta) invTransform.data = np.zeros(img.data.shape) # Add up all the detected lines over each other. The idea behind # adding up all the lines on top of each other is that pixels that # have larger number of detections are more likely to be in the # wavefront. Note that we are using th Hough transform - which is used # to detect lines - to detect and fill in a region. You might see this # as an abuse of the Hough transform! for i in range(0,len(indices[1])): nextLine = htLine(distances[i], theta[i], np.zeros(shape=img.data.shape)) invTransform = invTransform + nextLine detection.append(invTransform) return detection
def test_hough_line_peaks_single_angle(): # Regression test for gh-4814 # This code snippet used to raise an IndexError img = np.random.random((100, 100)) tested_angles = np.array([np.pi / 2]) h, theta, d = transform.hough_line(img, theta=tested_angles) accum, angles, dists = transform.hough_line_peaks(h, theta, d, threshold=2)
def test_hough_line_peaks_num(): img = np.zeros((100, 100), dtype=np.bool_) img[:, 30] = True img[:, 40] = True hspace, angles, dists = tf.hough_line(img) assert len(tf.hough_line_peaks(hspace, angles, dists, min_distance=0, min_angle=0, num_peaks=1)[0]) == 1
def test_hough_line_angles(): img = np.zeros((10, 10)) img[0, 0] = 1 out, angles, d = tf.hough_line(img, np.linspace(0, 360, 10)) assert_equal(len(angles), 10)
def igs1_measure_hough(realization,model,redshift=1.0,big_fiducial_set=False,threshold=0.1,bins=np.linspace(0.0,0.0014,50)): """ Measures all the statistical descriptors of a convergence map as indicated by the index instance """ logging.debug("Processing {0}".format(model.getNames(realization,z=redshift,big_fiducial_set=big_fiducial_set,kind="convergence"))) #Load the map conv_map = model.load(realization,z=redshift,big_fiducial_set=big_fiducial_set,kind="convergence") #Log to user logging.debug("Measuring hough histograms...") #Compute the hough transform linmap = conv_map.data > np.random.rand(*conv_map.data.shape) * threshold out,angle,d = hough_line(linmap) #Compute the histogram of the hough transform map h,b = np.histogram(out.flatten()*1.0/linmap.sum(),bins=bins) #Return return h
def test_hough_line_peaks_zero_input(): # Test to make sure empty input doesn't cause a failure img = np.zeros((100, 100), dtype='uint8') theta = np.linspace(0, np.pi, 100) hspace, angles, dists = transform.hough_line(img, theta) h, a, d = transform.hough_line_peaks(hspace, angles, dists) assert_equal(a, np.array([]))
def identify_based_on_lines(img_edges): # Find lines using hough transform hspace, theta, dists = transform.hough_line(img_edges) # Extract lines lines = transform.hough_line_peaks(hspace, theta, dists, num_peaks=10) # Convert lines to list of lines lines = np.array(list(zip(*lines)), dtype=[('hspace', np.uint64), ('angle', np.float), ('dist', np.float)]) shape_likeness = np.zeros(Shape.count) for i in range(1, Shape.count): shape = Shape.iterator[i] if shape == Shape.CAKE: hval = 0.0 if len(lines) >= 3: hval = abs(((lines[0][0] + lines[1][0]) * 0.5) - lines[2][0]) if hval >= 5.0: shape_likeness[i] = 0.0 else: shape_likeness[i] = 10.0 else: shape_likeness[i] = abs(shape.line_count - len(lines)) return shape_likeness
def test_hough_line_angles(): img = np.zeros((10, 10)) img[0, 0] = 1 out, angles, d = transform.hough_line(img, np.linspace(0, 360, 10)) assert_equal(len(angles), 10)
def get_orientation(image, debug=False): bin_image = (image > threshold_li(image)) * 1 dilated = scipy.ndimage.morphology.binary_dilation(bin_image, iterations=30) labeled, num_regions = mh.label(dilated) sizes = mh.labeled.labeled_size(labeled) mh.labeled.labeled_size(labeled) if len(sizes) > 2: too_small = np.where(sizes < np.flip(np.sort(sizes))[1]) labeled = mh.labeled.remove_regions(labeled, too_small) labeled = (labeled / np.max(np.unique(labeled))).astype(np.int) skeleton = skeletonize(labeled) h, theta, d = hough_line(skeleton) origin = np.array((0, skeleton.shape[1])) for _, angle, dist in zip(*hough_line_peaks(h, theta, d)): y0, y1 = (dist - origin * np.cos(angle)) / np.sin(angle) gradient = (y0 - y1) / origin[1] if debug == False: return math.degrees(np.arctan(gradient)) elif debug == True: f, ax = plt.subplots(figsize=(40, 20)) plt.imshow(bin_image) plt.show() f, ax = plt.subplots(figsize=(40, 20)) plt.imshow(dilated) plt.show() f, ax = plt.subplots(figsize=(40, 20)) plt.imshow(skeleton) plt.show() return math.degrees(np.arctan(gradient))
def scan_callback(msg): global ranges,image,h,theta,d,imagesize,delta_angle,min_angle,horizion_num ranges = np.array(msg.ranges) * 0.9998476951563913 min_angle = msg.angle_min max_angle = msg.angle_max delta_angle = msg.angle_increment horizion_num = len(ranges) # Map_size = np.max(ranges[np.logical_not(np.isinf(ranges))]) imagesize = int(round(Map_size/resolution)) image = np.zeros((2*imagesize, 2*imagesize)) #背景图为一片黑 # 画图 for i in range( 0, len(ranges) ): x = ranges[i] * math.cos( min_angle + i * delta_angle ) y = -ranges[i] * math.sin( min_angle + i * delta_angle ) if not np.isinf(x) and (not np.isinf(y)): if math.fabs(x) < Map_size - 0.1 and math.fabs(y) < Map_size - 0.1 : image[-int(round(x/resolution)) + imagesize ,-int(round(y/resolution)) + imagesize] = 255 # 进行hough线变换 h, theta, d = st.hough_line(image)
def detect_vertical_lines(data, max_deviation_from_vertical=1, row_begin=100, row_end=-100, min_distance=50): if "cropped_original" in data: image = data["cropped_original"] else: image = data["original"] image = np.gradient(image)[1] #Vertical component of gradient image = image[row_begin:row_end, :] h, theta, d = hough_line(image) #hough transform h[:, :90 - max_deviation_from_vertical] = 0 #Mask out areas that relate to non vertical lines h[:, 90 + max_deviation_from_vertical:] = 0 h = np.log(1 + h) #log scale for better visibility fx = [] for _, angle, dist in zip( *hough_line_peaks(h, theta, d, min_distance=min_distance)): y0 = (dist) / np.sin(angle) #y for x = 0 y1 = (dist - image.shape[1] * np.cos(angle)) / np.sin( angle) #y for x = image.shape[1] intercept = y0 slope = (y1 - y0) / float(image.shape[1]) fx.append([slope, intercept]) data["houghlines"] = fx #ax.plot(x, intercept+x*slope, '-r') return data
def test1(): X, y = LR.make_data() image = scatter2image(X, y) accumulator, thetas, rhos = transform.hough_line( image) # hough_line(image) show_transform(accumulator, 'hough_transform') show_line(image, accumulator, thetas, rhos, 50, 'hough_line')
def jet_detect(img, calibratemean, calibratestd, x): mean, std = image_stats(img) # compare mean & calibratemean if (mean < calibratemean * 0.8) or (mean > calibratemean * 1.2): print('no jet') for c in range(x): try: # binary = (img / (mean + 2 * std * 0.90 ** c)).astype(np.uint8) # binary = cv2.adaptiveThreshold(img, 1, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 50, 2) # binary = cv2.bitwise_not(imagem) # lines = cv2.HoughLines(binary, 1, np.radians(0.25), 30) # rho, theta = lines[0][0] binary = canny(img, sigma=2, use_quantiles=True, low_threshold=0.9, high_threshold=0.99) fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(8, 3), sharex=True, sharey=True) ax1.imshow(img, cmap=plt.cm.gray) ax2.imshow(binary, cmap=plt.cm.gray) plt.show() h, theta, d = hough_line(binary) accum, angles, ds = hough_line_peaks(h, theta, d, min_distance=2) print(accum) print(angles) print(ds) # if (theta > math.radians(45)) and (theta < math.radians(135)): # print('invalid jet') # if (get_jet_width(img, rho, theta) * pxsize > 0.1): # print('invalid jet') # for rho, theta in lines[0]: # jetValid = true # if (theta > math.radians(70)): # jetValid = False # width = get_jet_width(binary, rho, theta) # if (width > [x]): # jetValid = False # if (jetValid == False): # reject jet except Exception: print(c) continue else: # show binary image # cv2.imshow('binary', binary) # cv2.waitKey(0) # cv2.destroyAllWindows() # return rho, theta # return 0, 0 return angles[0], ds[0] raise ValueError('unable to detect jet')
def isolate_board(img): """ INPUT: img -- Image containing a Sudoku board OUTPUT: img -- Image cropped to contain only the Sudoku board """ edges = canny(img, sigma=1).astype(np.uint8) test_angles = np.linspace(-np.pi / 2, np.pi / 2, 360) # Sweep -90° to +90° h, theta, d = hough_line(edges, theta=test_angles) top = img.shape[0] + 1 bottom = -1 left = img.shape[1] + 1 right = -1 # Horizontal Line: theta ~= pi/2 # Vertical Line: theta ~= 0 for _, angle, dist in zip(*hough_line_peaks(h, theta, d)): # If line is Vertical if -45 < np.rad2deg(angle) < 45: # If line is furthest Left if dist < left: left = dist # If line is furthest Right if dist > right: right = dist else: # Line is Horizontal # If line is furthest Down if dist > bottom: bottom = dist # If line is furthest Up if dist < top: top = dist return img[int(top):int(bottom), int(left):int(right)]
def estimate_corner_lines(corner_region, corner_type, image_size): ''' Estimate the line parameters for the edges of the given marker corner Inputs: - corner_region: regionprops for the given corner of the marker - corner_type: either 'BL' for bottom-left or 'TR' for top-right - image_size: tuple of original camera image's size Return: A list of length 2 holding the line parameters of horizontal and vertical edges of the marker ''' corner_miny, corner_minx, corner_maxy, corner_maxx = corner_region.bbox # Pad the corner image to match the size of the entire image corner_image = util.pad(corner_region.intensity_image, ((corner_miny, image_size[0] - corner_maxy), (corner_minx, image_size[1] - corner_maxx)), mode='constant', constant_values=0) # Perform edge detection and Hough line transform corner_edges = feature.canny(corner_image, sigma=0) corner_hough = transform.hough_line(corner_edges, theta=np.linspace( -np.pi / 2, np.pi / 2, 360)) corner_hough_peaks = list( zip(*transform.hough_line_peaks( *corner_hough, min_angle=45, num_peaks=2))) corner_lines = [] def is_horizontal(peak): return abs(np.rad2deg(peak[1])) > 75 def is_vertical(peak): return abs(np.rad2deg(peak[1])) <= 15 # Categorized the detected lines as vertical or horizontal horizontal_peaks = list(filter(is_horizontal, corner_hough_peaks)) vertical_peaks = list(filter(is_vertical, corner_hough_peaks)) # Add the first estimated horizontal line if horizontal_peaks: corner_lines.append(horizontal_peaks[0]) else: # Create a horizontal line from the bottom edge (if BL type) or top edge (if TR type) angle = np.pi / 2 dist = corner_maxy if corner_type == 'BL' else corner_miny corner_lines.append((0, angle, dist)) # Add the first estimated vertical line if vertical_peaks: corner_lines.append(vertical_peaks[0]) else: # Create a vertical line from the left edge (if BL type) or right edge (if TR type) angle = 0.001 dist = corner_minx if corner_type == 'BL' else corner_maxx corner_lines.append((0, angle, dist)) return corner_lines
def detect_line_p(route): line_img = cv2.imread(route) line_img = np.copy(line_img) line_img_copy = cv2.cvtColor(line_img, cv2.COLOR_BGR2RGB) line_img_gray = cv2.cvtColor(line_img_copy, cv2.COLOR_RGB2GRAY) # detect edge line_edges = cv2.Canny(line_img_gray, 100, 120) cv2.imshow("edge", line_edges) # hough transform h, angles, d = st.hough_line(line_edges) lines = cv2.HoughLines(line_edges, 1, np.pi / 180, 180) img_h = np.copy(line_img_copy) for line in lines: rho, theta = line[0] a = np.cos(theta) b = np.sin(theta) x0 = a * rho y0 = b * rho x1 = int(x0 + 1000 * (-b)) y1 = int(y0 + 1000 * (a)) x2 = int(x0 - 1000 * (-b)) y2 = int(y0 - 1000 * (a)) cv2.line(img_h, (x1, y1), (x2, y2), (0, 255, 0), 2) return np.log(1 + h), img_h
def calculate(self, image: np.ndarray, disk_size: int=9, mean_threshold: int=100, min_object_size: int=750) -> float: # Find edges that have a strong vertical direction vertical_edges = sobel_v(image) # Separate out the areas where there is a large amount of vertically-oriented stuff segmentation = self._segment_edge_areas(vertical_edges, disk_size, mean_threshold, min_object_size) # Draw a line that follows the center of the segments at each point, which should be roughly vertical # We should expect this to give us four approximately-vertical lines, possibly with many gaps in # each line skeletons = skeletonize(segmentation) # Use the Hough transform to get the closest lines that approximate those four lines hough = transform.hough_line(skeletons, np.arange(-constants.FIFTEEN_DEGREES_IN_RADIANS, constants.FIFTEEN_DEGREES_IN_RADIANS, 0.0001)) # Create a list of the angles (in radians) of all of the lines the Hough transform produced, with 0.0 # being completely vertical # These angles correspond to the angles of the four sides of the channels, which we need to # correct for angles = [angle for _, angle, dist in zip(*transform.hough_line_peaks(*hough))] if not angles: raise ValueError("Image rotation could not be calculated. Check the images to see if they're weird.") else: # Get the average angle and convert it to degrees offset = sum(angles) / len(angles) * 180.0 / math.pi if offset > constants.ACCEPTABLE_SKEW_THRESHOLD: log.warn("Image is heavily skewed. Check that the images are valid.") return offset
def _determine_rotation_offset(image): """ Finds rotational skew so that the sides of the central trench are (nearly) perfectly vertical. :param image: raw image data in a 2D (i.e. grayscale) numpy array :type image: np.array() """ segmentation = create_vertical_segments(image) # Draw a line that follows the center of the segments at each point, which should be roughly vertical # We should expect this to give us four approximately-vertical lines, possibly with many gaps in each line skeletons = skeletonize(segmentation) # Use the Hough transform to get the closest lines that approximate those four lines hough = transform.hough_line(skeletons, np.arange(-Constants.FIFTEEN_DEGREES_IN_RADIANS, Constants.FIFTEEN_DEGREES_IN_RADIANS, 0.0001)) # Create a list of the angles (in radians) of all of the lines the Hough transform produced, with 0.0 being # completely vertical # These angles correspond to the angles of the four sides of the channels, which we need to correct for angles = [angle for _, angle, dist in zip(*transform.hough_line_peaks(*hough))] if not angles: log.warn("Image skew could not be calculated. The image is probably invalid.") return 0.0 else: # Get the average angle and convert it to degrees offset = sum(angles) / len(angles) * 180.0 / math.pi if offset > Constants.ACCEPTABLE_SKEW_THRESHOLD: log.warn("Image is heavily skewed. Check that the images are valid.") return offset
def determine_skew(img): edges = canny(img, sigma=3.0) h, a, d = hough_line(edges) _, ap, _ = hough_line_peaks(h, a, d, num_peaks=10) absolute_deviations = [np.abs(np.pi / 4 - np.abs(k)) for k in ap] average_deviation = np.mean(np.rad2deg(absolute_deviations)) ap_deg = [np.rad2deg(x) for x in ap] bin_0_45 = [] bin_45_90 = [] bin_0_45n = [] bin_45_90n = [] for ang in ap_deg: deviation_sum = int(90 - ang + average_deviation) if compare_sum(deviation_sum): bin_45_90.append(ang) continue deviation_sum = int(ang + average_deviation) if compare_sum(deviation_sum): bin_0_45.append(ang) continue deviation_sum = int(-ang + average_deviation) if compare_sum(deviation_sum): bin_0_45n.append(ang) continue deviation_sum = int(90 + ang + average_deviation) if compare_sum(deviation_sum): bin_45_90n.append(ang) angles = [bin_0_45, bin_45_90, bin_0_45n, bin_45_90n] lmax = 0 for j in range(len(angles)): l = len(angles[j]) if l > lmax: lmax = l maxi = j if lmax: ans_arr = get_max_freq_elem(angles[maxi]) ans_res = np.mean(ans_arr) else: ans_arr = get_max_freq_elem(ap_deg) ans_res = np.mean(ans_arr) data = { "Average Deviation from pi/4": average_deviation, "Estimated Angle": ans_res, "Angle bins": angles } return data
def manualTrack(image, bckMean, idx=-1): contrast = 17. radius = 30. plt.clf() stopTrack = False plt.imshow(image, cmap='gray') rows, cols = image.shape plt.title('Click on the manipulator; Frame: %i' % idx) plt.draw() plt.pause(0.001) manip = np.asarray(plt.ginput(1, timeout=0)) if len(manip) == 0: y0 = np.NaN y1 = np.NaN thetaInit = np.NaN d = np.NaN stopTrack = True return y0, y1, thetaInit, d, stopTrack else: roiRow, roiCol = circle(manip[0, 1], manip[0, 0], radius) # make sure the roi is not too big roiRow[roiRow >= rows] = rows - 1 roiCol[roiCol >= cols] = cols - 1 # imROI = 255 * np.ones_like(image) imROI[roiRow, roiCol] = image[roiRow, roiCol] thresh = cv2.threshold(image[roiRow, roiCol], 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[0] # BW = imROI < (bckMean - contrast) BW = imROI < thresh # BW = dil_skel(BW) h, theta, d = hough_line(BW) try: _, thetaInit, d = hough_line_peaks(h, theta, d, min_distance=1, num_peaks=1) except: y0 = np.NaN y1 = np.NaN thetaInit = np.NaN d = np.NaN stopTrack = True return y0, y1, thetaInit, d, stopTrack y0 = (d - 0 * np.cos(thetaInit)) / np.sin(thetaInit) y1 = (d - cols * np.cos(thetaInit)) / np.sin(thetaInit) if len(y0) == 0: stopTrack = True plt.clf() thetaInit = np.mean(thetaInit) return y0, y1, thetaInit, d, stopTrack
def radonhoughcomp(Data): ############################################################################### # Hough and Radon Transforms ############################################################################### thresh = threshold_otsu(Data) binary = Data > thresh h, theta, d = hough_line(binary) sinogram = radon(binary, circle=False) ############################################################################### # Plots ############################################################################### fig, axes3 = plt.subplots(nrows=2, ncols=2, figsize=(12, 8)) ax3 = axes3.ravel() ax3[0] = plt.subplot(2, 2, 1) ax3[1] = plt.subplot(2, 2, 2) ax3[2] = plt.subplot(2, 2, 3) ax3[3] = plt.subplot(2, 2, 4) ax3[0].imshow(Data, cmap=plt.cm.gray, aspect='auto') ax3[0].set_title("Original") #ax3[0].set_ylim([200,0]) ax3[0].axis('off') ax3[1].imshow(binary, cmap=plt.cm.gray, aspect='auto') row1, col1 = binary.shape for _, angle, dist in zip(*hough_line_peaks(h, theta, d)): y0 = (dist - 0 * np.cos(angle)) / np.sin(angle) y1 = (dist - col1 * np.cos(angle)) / np.sin(angle) ax3[1].plot((0, col1), (y0, y1), '-r') ax3[1].axis((0, col1, row1, 0)) ax3[1].set_title('After Transform') #ax3[1].set_ylim([200,0]) ax3[1].axis('off') ax3[2].imshow(sinogram, cmap=plt.cm.gray, extent=(0, 180, 0, sinogram.shape[0]), aspect='auto') ax3[2].set_title("Radon transform") ax3[2].set_xlabel("Angles (degrees)") ax3[2].set_ylabel("Distance (pixels)") ax3[3].imshow( np.log(1 + h), extent=[np.rad2deg(theta[-1]), np.rad2deg(theta[0]), 0, d[0] * -1], cmap=plt.cm.gray, aspect='auto') ax3[3].set_title('Hough transform') ax3[3].set_xlabel('Angles (degrees)') ax3[3].set_ylabel('Distance (pixels)') plt.savefig('radonhoughcomp.png') plt.show()
def execute(self, _image): # 避免计算耗时过长 resized_img = resize_with_long_side(_image, 1024) gray_image = cv2.cvtColor(resized_img, cv2.COLOR_BGR2GRAY) edges = canny(gray_image, sigma=self.sigma) h, a, d = hough_line(edges) _, candidate_angle_bins, _ = hough_line_peaks(h, a, d, num_peaks=self.num_peaks) if len(candidate_angle_bins) == 0: return _image absolute_deviations = [ calculate_deviation(m_angle) for m_angle in candidate_angle_bins ] average_deviation = np.mean(np.rad2deg(absolute_deviations)) angle_degrees = [np.rad2deg(x) for x in candidate_angle_bins] bin_0_45 = [] bin_45_90 = [] bin_0_45n = [] bin_45_90n = [] low_bound_of_angle = 44 high_bound_of_angle = 46 for m_angle_degree in angle_degrees: for m_bin, m_new_angle_degree in zip( [bin_45_90, bin_0_45, bin_0_45n, bin_45_90n], [ 90 - m_angle_degree, m_angle_degree, -m_angle_degree, 90 + m_angle_degree ]): deviation_sum = int(m_new_angle_degree + average_deviation) if low_bound_of_angle <= deviation_sum <= high_bound_of_angle: m_bin.append(m_angle_degree) candidate_angle_bins = [bin_0_45, bin_45_90, bin_0_45n, bin_45_90n] selected_angle_bin = 0 selected_angle_bin_length = len(candidate_angle_bins[0]) for j in range(1, len(candidate_angle_bins)): m_len_angles = len(candidate_angle_bins[j]) if m_len_angles > selected_angle_bin_length: selected_angle_bin_length = m_len_angles selected_angle_bin = j if selected_angle_bin_length: candidate_degrees = get_max_frequency_element( candidate_angle_bins[selected_angle_bin]) mean_degree = np.mean(candidate_degrees) else: candidate_degrees = get_max_frequency_element(angle_degrees) mean_degree = np.mean(candidate_degrees) target_to_rotate_angle = mean_degree if 0 <= mean_degree <= 90: target_to_rotate_angle = mean_degree - 90 if -90 <= mean_degree < 0: target_to_rotate_angle = 90 + mean_degree rotated_image, _ = rotate_degree_img(_image, -target_to_rotate_angle) return rotated_image
def test_hough_line_peaks_num(): img = np.zeros((100, 100), dtype=bool) img[:, 30] = True img[:, 40] = True hspace, angles, dists = transform.hough_line(img) assert len(transform.hough_line_peaks(hspace, angles, dists, min_distance=0, min_angle=0, num_peaks=1)[0]) == 1
def applyHough(nAngles, img): # hough # Classic straight-line Hough transform # Set a precision of 0.5 degree. tested_angles = np.linspace(-np.pi / 2, np.pi / 2, nAngles) h, theta, d = hough_line(img, theta=tested_angles) return(h, theta, d)
def test_hough_line_peaks_num(): img = np.zeros((100, 100), dtype=np.bool_) img[:, 30] = True img[:, 40] = True hspace, angles, dists = tf.hough_line(img) with expected_warnings(['`background`']): assert len(tf.hough_line_peaks(hspace, angles, dists, min_distance=0, min_angle=0, num_peaks=1)[0]) == 1
def roll_from_disp(disp): h, theta, d = hough_line( (cfg['test_disp'][0] < disp) & (disp < cfg['test_disp'][1]), theta=linspace(deg2rad(90 - 30), deg2rad(90 + 30), 250)) _, angles, dists = hough_line_peaks(h, theta, d, num_peaks=1) if len(angles) == 0: angles = [NaN] return 90 - rad2deg(angles[0])
def rotate_images(self): # https://stackoverflow.com/a/56675787 # https: // scikit - image.org / docs / dev / auto_examples / edges / plot_line_hough_transform.html image_count = len(self.images) current_image = 1 for image in self.images: image_path = f'./data/01_raw/{image}' # Load Image loaded_image = cv2.imread(image_path) # Convert to grayscale gray = cv2.cvtColor(loaded_image, cv2.COLOR_BGR2GRAY) # Convert non-black pixels to pure white. Creates white box (image) on black background thresh = cv2.threshold(gray, 1, 255, cv2.THRESH_BINARY)[1] # Smooth thresh = cv2.erode(thresh, None, iterations=2) thresh = cv2.dilate(thresh, None, iterations=4) # Resize thresh = cv2.resize(thresh, (0, 0), fx=0.25, fy=0.25) # Find edges of white box edges = cv2.Canny(thresh, 100, 200) img = edges row_length = len(img[0]) - 1 # Draw a horizontal line to use to create an angle with the satellite image border width, height = img.shape thickness = 5 y_offset = int(ceil(height / 2)) for x in range(1, thickness): rr, cc = line(x + y_offset, 1, x + y_offset, row_length) img[rr, cc] = 1 # Crop image (only working with top half) y = 0 x = 0 h = height - int(ceil(height / 2)) w = width crop = img[y:y + h, x:x + w] # Perform Hough Transformation to detect lines hspace, angles, distances = hough_line(crop) # Find angle angle = [] for _, a, distances in zip( *hough_line_peaks(hspace, angles, distances)): angle.append(a) # Obtain angle for each line angles = [a * 180 / np.pi for a in angle] # Rotate image to make it line up square rotated = imutils.rotate(loaded_image, angles[0]) # Save image save_path = f'./data/02_preprocessing/{image}' cv2.imwrite(save_path, rotated) print(f'Fixed image rotation: \t {current_image}/{image_count}') current_image += 1
def test_hough_line_peaks_dist(): img = np.zeros((100, 100), dtype=np.bool_) img[:, 30] = True img[:, 40] = True hspace, angles, dists = tf.hough_line(img) assert len(tf.hough_line_peaks(hspace, angles, dists, min_distance=5)[0]) == 2 assert len(tf.hough_line_peaks(hspace, angles, dists, min_distance=15)[0]) == 1
def test_hough_line_peaks_angle(): img = np.zeros((100, 100), dtype=np.bool_) img[:, 0] = True img[0, :] = True hspace, angles, dists = tf.hough_line(img) assert len(tf.hough_line_peaks(hspace, angles, dists, min_angle=45)[0]) == 2 assert len(tf.hough_line_peaks(hspace, angles, dists, min_angle=90)[0]) == 1 theta = np.linspace(0, np.pi, 100) hspace, angles, dists = tf.hough_line(img, theta) assert len(tf.hough_line_peaks(hspace, angles, dists, min_angle=45)[0]) == 2 assert len(tf.hough_line_peaks(hspace, angles, dists, min_angle=90)[0]) == 1 theta = np.linspace(np.pi / 3, 4. / 3 * np.pi, 100) hspace, angles, dists = tf.hough_line(img, theta) assert len(tf.hough_line_peaks(hspace, angles, dists, min_angle=45)[0]) == 2 assert len(tf.hough_line_peaks(hspace, angles, dists, min_angle=90)[0]) == 1
def test_hough_line_peaks_dist(): img = np.zeros((100, 100), dtype=np.bool_) img[:, 30] = True img[:, 40] = True hspace, angles, dists = transform.hough_line(img) assert len(transform.hough_line_peaks(hspace, angles, dists, min_distance=5)[0]) == 2 assert len(transform.hough_line_peaks(hspace, angles, dists, min_distance=15)[0]) == 1
def skew_angle_hough_transform(image): edges = canny(image) tested_angles = np.deg2rad(np.arange(0.1, 180.0)) h, theta, d = hough_line(edges, theta=tested_angles) accum, angles, dists = hough_line_peaks(h, theta, d) most_common_angle = mode(np.around(angles, decimals=2))[0] skew_angle = np.rad2deg(most_common_angle - np.pi / 2) img_rotated = rotate(image, skew_angle, resize=True, mode='edge') return img_rotated
def constructCorridorsByHT(**kwargs): "Construct corridors based on the lines extracted by Hough transform" xyz_min = kwargs['xyz_min'] xyz_max = kwargs['xyz_max'] pts_1 = kwargs['points'] cellsize = kwargs['cellsize'] threshold_line = kwargs['HF_peaks_threshold'] maxdist = kwargs['maxdist'] threshold_discontinuity = kwargs['discontinuity_threshold'] buffer_size = kwargs['buffer_size'] # a = {'min_xyz':xyz_min, 'max_xyz':xyz_max, 'pts':pts_1, 'cellsize':1} img_xy = pointsToRaster(**a) # rtn # Hough transform tested_angles = np.linspace(0, 2*np.pi, 360) h, theta, d = hough_line(img_xy, theta = tested_angles) hough_peaks = hough_line_peaks(h, theta, d, threshold=threshold_line) # filter the short lines based on hough peaks and raster image img_xy a = {'img': img_xy, 'peaks':zip(*hough_peaks), 'maxdist':maxdist} img_base = houghToRasterByCellID(**a) # rtn # calcualte the length of lines. the number of cells on lines a = {'img': img_base, 'peaks':zip(*hough_peaks), 'maxdist':maxdist} hl = recordHoughLines(**a) # rtn hough-lines hl = np.array(hl) # judge the extent of a line discontinuity. a = {'hough-lines': hl, 'maxdist': 1, 'img_base': img_base} lid = evaluateLinesDiscontinuity(**a) # rtn discontinuity of lines lid = np.array(lid) # remove the lines with long discontinuity idx = np.argwhere(lid < threshold_discontinuity) hltemp = hl[idx.ravel()] # generate new raster image with continuous lines a = {'img':img_xy, 'HLine':hltemp} img_temp = generateCorridorByLine(**a) # rtn image with continuous lines # construct corridors based on img_temp and buffer operation line_params = [] for h in hltemp: line_params.append(h.coord) a = {'img': img_base, 'peaks':line_params, 'maxdist':buffer_size} img_corridors = generateBuffer(**a) # rtn corridors # generate image buffer array lineBufferArray = [] # rtn the collection of corridors for h in hltemp: a = {'img': img_base, 'peaks':[h.coord], 'maxdist':buffer_size} img = generateBuffer(**a) lineBufferArray.append(img) # rtn = {'img_xy': img_xy, 'img_base': img_base, 'hough_lines': hl, 'discontinuity': lid, 'img_lines': img_temp, 'img_corridors': img_corridors, 'corridors': lineBufferArray } return rtn
def deskew(image): edges = canny(image, low_threshold=50, high_threshold=150, sigma=2) harris = corner_harris(edges) tested_angles = np.linspace(-np.pi / 2, np.pi / 2, 360) h, theta, d = hough_line(harris, theta=tested_angles) out, angles, d = hough_line_peaks(h, theta, d) rotation_number = np.average(np.degrees(angles)) if rotation_number < 45 and rotation_number != 0: rotation_number += 90 return rotation_number
def detect_lines(img): # skeletonized_image = skeletonize(img) # skeletonized_image = canny(img) skeletonized_image = img tested_angles = np.linspace(-np.pi / 2, np.pi / 2, 360) h, theta, d = hough_line(skeletonized_image, theta=tested_angles) # fig, axes = plt.subplots(figsize=(15, 6)) # axes.imshow(skeletonized_image, cmap=cm.gray) origin = np.array((0, skeletonized_image.shape[1]-1)) peaks = zip(*hough_line_peaks(h, theta, d, threshold=0.3*np.max(h))) linesArr = [] for _, angle, dist in peaks: if abs(90 - abs(np.rad2deg(angle)) > 3): # if angle is not close to 90/-90 degress neglect it (we detect horizontal lines only) continue if(abs(np.rad2deg(angle)) > 0.5): #if angle not equal zero y0, y1 = (dist - origin * np.cos(angle)) / np.sin(angle) else: #if angle zero y0 = 0 y1 = skeletonized_image.shape[0] - 1 origin[0] = dist origin[1] = dist point0 = [origin[0], y0] point1 = [origin[1], y1] # print(y0, y1) if(len([index for index,value in enumerate(linesArr) \ if \ ( abs(value[0][1] - y0) < 5 and abs(value[1][1] - y1) < 5 ) \ or ( value[0][1] > y0 and value[1][1] < y1 ) \ or ( value[0][1] < y0 and value[1][1] > y1 ) \ ]) == 0): #If this line nearly approaches or intersects a previous line, don't take it linesArr.append([point0, point1]) else: continue # axes.plot(origin, (y0, y1), '-r') origin[0] = 0 origin[1] = skeletonized_image.shape[1] - 1 # axes.set_xlim(origin) # axes.set_ylim((skeletonized_image.shape[0], 0)) # axes.set_axis_off() # axes.set_title('Detected lines') # plt.tight_layout() # plt.show() linesArr.sort(key=line_sort_key) #sort by the y component of the first point in each line return np.array(linesArr)
def align_with_boarder(image, sigma=1): edges = ft.canny(image, sigma=sigma) # edges = abs(fil.sobel_v(image)) h, theta, d = tf.hough_line(edges) a, rot_angle, c = tf.hough_line_peaks(h, theta, d, min_distance=0) image = rotate(image, np.rad2deg(rot_angle[0])) return image
def test_ideal_tfr(self): """Test if the ideal TFR can be found using the instantaneous frequency laws.""" _, iflaw1 = fmlin(128, 0.0, 0.2) _, iflaw2 = fmlin(128, 0.3, 0.5) iflaws = np.c_[iflaw1, iflaw2].T tfr, _, _ = pproc.ideal_tfr(iflaws) tfr[tfr == 1] = 255 tfr = tfr.astype(np.uint8) hspace, angles, dists = hough_line(tfr) for x in hough_line_peaks(hspace, angles, dists): self.assertEqual(len(x), 2)
def test_hough_line_peaks(): img = np.zeros((100, 150), dtype=int) rr, cc = line(60, 130, 80, 10) img[rr, cc] = 1 out, angles, d = tf.hough_line(img) out, theta, dist = tf.hough_line_peaks(out, angles, d) assert_equal(len(dist), 1) assert_almost_equal(dist[0], 80.723, 1) assert_almost_equal(theta[0], 1.41, 1)
def houghSides(bottle, edges, threshold, left): h, theta, d = hough_line(edges) accum = zip(*hough_line_peaks(h, theta, d)) sortedAccum = sorted(accum, key=getKey, reverse=True) sortedAccumR = [sa for sa in sortedAccum if sa[2] > 200] sortedAccumL = [sa for sa in sortedAccum if sa[2] <= 200] if left: hpeak, angle, dist = sortedAccumL[0] else: hpeak, angle, dist in sortedAccumR[0] return (1, dist, angle)
def test_hough_line_peaks_ordered(): # Regression test per PR #1421 testim = np.zeros((256, 64), dtype=np.bool) testim[50:100, 20] = True testim[85:200, 25] = True testim[15:35, 50] = True testim[1:-1, 58] = True hough_space, angles, dists = tf.hough_line(testim) hspace, _, _ = tf.hough_line_peaks(hough_space, angles, dists) assert hspace[0] > hspace[1]
def check_door(image, Pw_corners, Pi_corners, door_edges, required_matching_ratio=0.7, verbose=0): """Check if door is closed.""" results = {} image_sobel, image_edges = detect_edges(image) # Detect lines with Hough transform hough_accumulator, angles, dists = hough_line(image_edges) hspace, angles, dists = hough_line_peaks( hough_accumulator, angles, dists, threshold=150.0) # Estimate camera transformation by minimizing the distance between # calibration points params = optimize_transform(camera_params, Pw_corners, Pi_corners) if verbose >= 1: print("Parameters: %s" % np.round(params, 3)) cam2world = transform_from(matrix_from_euler_xyz(params[:3]), params[3:6]) kappa = params[-1] W2I = partial(world2image, cam2world=cam2world, kappa=kappa, **camera_params) # Get edge pixels in vicinity of lines Pi_line_points = check_edge_is_on_line(image_edges, angles, dists) if len(Pi_line_points) == 0: if verbose >= 1: print("No lines detected, assume that door is closed") door_closed = True else: # Check how good the edges of the door projected to the image match # detected edge pixels that correspond to lines matchings = [check_line_is_edge(edge, Pi_line_points, cam2world, kappa, camera_params) for edge in door_edges] results["door_edges_in_image"] = [m[0] for m in matchings] ratios = np.array([m[1] for m in matchings]) if verbose >= 1: print(("Matching ratios: " + ", ".join(["%.2f"] * len(ratios))) % tuple(100 * ratios)) door_closed = np.any(ratios > required_matching_ratio) results["cam2world"] = cam2world results["Pi_line_points"] = Pi_line_points results["image_sobel"] = image_sobel results["image_edges"] = image_edges results["lines"] = (angles, dists) return door_closed, W2I, results
def test_hough_line(): # Generate a test image img = np.zeros((100, 150), dtype=int) rr, cc = line(60, 130, 80, 10) img[rr, cc] = 1 out, angles, d = tf.hough_line(img) y, x = np.where(out == out.max()) dist = d[y[0]] theta = angles[x[0]] assert_almost_equal(dist, 80.723, 1) assert_almost_equal(theta, 1.41, 1)
def test_hough(): # Generate a test image img = np.zeros((100, 100), dtype=int) for i in range(25, 75): img[100 - i, i] = 1 out, angles, d = tf.hough_line(img) y, x = np.where(out == out.max()) dist = d[y[0]] theta = angles[x[0]] assert_equal(dist > 70, dist < 72) assert_equal(theta > 0.78, theta < 0.79)
def findLines(img): r = img[..., 0] g = img[..., 1] b = img[..., 2] # Add all edges together edges = findEdges(r) + findEdges(g) + findEdges(b) # Dilate to make the edges thicker dilatedEdges = dilation(edges) # To a Hough transform to find the lines h, theta, d = hough_line(dilatedEdges) return edges, dilatedEdges, (h, theta, d)
def hough_transform(binary_image, theta=np.linspace(0, np.pi / 2, 3, endpoint=True)): """Compute a Hough Transform on a binary image to detect straight lines Args: binary_image: 2D image, where 0 is off and 255 is on. Returns: (ndarray, array, array): Bins, angles, distances Values of the bins after the Hough Transform, where the value at (i, j) is the number of 'votes' for a straight line with distance[i] perpendicular to the origin and at angle[j]. Also returns the corresponding array of angles and the corresponding array of distances. """ hspace, angles, distances = hough_line(binary_image, theta) return hspace.astype(np.float32), angles, distances
def test_example(): # Construct toydata image = np.zeros((100, 100)) idx = np.arange(25, 75) image[idx[::-1], idx] = 255 image[idx, idx] = 255 # Classic straight-line Hough transform h, theta, d = hough_line(image) # plot plt.figure(figsize=(8, 4)) plt.subplot(131) plt.imshow(image, cmap=plt.cm.gray) plt.title('Input image') plt.subplot(132) plt.imshow(np.log(1 + h), extent=[np.rad2deg(theta[-1]), np.rad2deg(theta[0]), d[-1], d[0]], cmap=plt.cm.gray, aspect=1/1.5) plt.title('Hough transform') plt.xlabel('Angles (degrees)') plt.ylabel('Distance (pixels)') plt.subplot(133) plt.imshow(image, cmap=plt.cm.gray) rows, cols = image.shape for _, angle, dist in zip(*hough_line_peaks(h, theta, d)): y0 = (dist - 0 * np.cos(angle)) / np.sin(angle) y1 = (dist - cols * np.cos(angle)) / np.sin(angle) plt.plot((0, cols), (y0, y1), '-r') plt.axis((0, cols, rows, 0)) plt.title('Detected lines')
def get_features(x): features = [] image = np.array([x]) image.resize((28, 28)) binary_image = filters.threshold_adaptive(image, 9) angles = np.linspace(0, 1, 8) * PI h, _, _ = transform.hough_line(filters.sobel(binary_image), theta=angles) h_sum = [ [sum(row[start:start+5]) for start in xrange(0, 75, 5)] for row in zip(*h) ] features.extend(np.array(h_sum).reshape(1, -1).tolist()[0]) # moments = measure.moments(binary_image) # hu_moments = measure.moments_hu(moments) # # reshape: -1 as a dimension size makes the dimension implicit # features.extend(moments.reshape((1, -1)).tolist()[0]) # features.extend(hu_moments.reshape((1, -1)).tolist()[0]) # h_line, _, _ = transform.hough_line(binary_image) # features.extend(np.array(h_line).reshape((1, -1)).tolist()[0]) return features
probabilistic_hough_line) from skimage.feature import canny from skimage import data import matplotlib.pyplot as plt from matplotlib import cm # Constructing test image image = np.zeros((100, 100)) idx = np.arange(25, 75) image[idx[::-1], idx] = 255 image[idx, idx] = 255 # Classic straight-line Hough transform h, theta, d = hough_line(image) # Generating figure 1 fig, axes = plt.subplots(1, 3, figsize=(15, 6)) ax = axes.ravel() ax[0].imshow(image, cmap=cm.gray) ax[0].set_title('Input image') ax[0].set_axis_off() ax[1].imshow(np.log(1 + h), extent=[np.rad2deg(theta[-1]), np.rad2deg(theta[0]), d[-1], d[0]], cmap=cm.gray, aspect=1/1.5) ax[1].set_title('Hough transform') ax[1].set_xlabel('Angles (degrees)') ax[1].set_ylabel('Distance (pixels)')
def interest_region(image, plot_image = 0): # constant th_x = 0.5 th_y = 0.5 lid_thickness = 680 bot_thickness = 230 side_thickness = 80 rotation_limit = 2 angle_u_lim = (90.0 + rotation_limit) / 180.0 * np.pi angle_d_lim = (90.0 - rotation_limit) / 180.0 * np.pi #Grayscale Conversion and Edge Detection if(len(image.shape)>2): image = rgb2gray(image) img_edge = canny(image, sigma = 3) #Image Rotation h, theta, d = hough_line(img_edge) h_peak, theta_peak, d_peak = hough_line_peaks(h, theta, d) theta_rotation = theta[np.where(np.absolute(theta_peak)<=angle_u_lim)] theta_rotation = theta_rotation[np.where(np.absolute(theta_rotation)>=angle_d_lim)] if(theta_rotation.size): rotate_angle = np.pi/2-np.absolute(np.mean(theta_rotation)) img_rotate = rotate(img_edge,rotate_angle*180) #rectangular region selection index = np.where(img_rotate>0) [hy,b] = np.histogram(index[0],100) by = (b[0:(len(b)-1)]+b[1:len(b)])/2 [hx,b] = np.histogram(index[1],100) bx = (b[0:(len(b)-1)]+b[1:len(b)])/2 temp = by[np.where(hy>=th_y*np.mean(hy))] if(len(temp)>0): bottom = np.amin(temp) top = np.amax(temp) else: bottom = 450 top = 1500 temp = bx[np.where(hx>=th_x*np.mean(hx))] if(len(temp)>0): left = np.amin(temp)+lid_thickness right = np.amax(temp)-bot_thickness if (right <= left): left = np.amin(temp)+int(lid_thickness/2) right = np.amax(temp)+int(lid_thickness/2) else: left = 1700 right = 3600-bot_thickness bottom = bottom + side_thickness top = top - side_thickness #print [bottom,top,left,right]; image_rotation = rotate(image,rotate_angle*180) interest_image = image_rotation[bottom:top,left:right]; if(plot_image == 1): fig, ax = plt.subplots(2,3) ax[0,0].imshow(image,cmap=plt.cm.gray) ax[0,0].set_title('Original Image') ax[0,1].imshow(img_edge,cmap=plt.cm.gray) ax[0,1].set_title('Canny Endge Detection') ax[0,2].imshow(image, cmap=plt.cm.gray) rows, cols = image.shape for _, angle, dist in zip(*hough_line_peaks(h, theta, d)): y0 = (dist - 0 * np.cos(angle)) / np.sin(angle) y1 = (dist - cols * np.cos(angle)) / np.sin(angle) ax[0,2].plot((0, cols), (y0, y1),'-r') ax[0,2].axis((0, cols, rows, 0)) ax[0,2].set_title('Detected lines') ax[0,2].set_axis_off() ax[1,0].imshow(img_rotate,cmap=plt.cm.gray) ax[1,0].set_title('Image Edge after Rotation') ax[1,1].scatter(index[1],index[0]) ax[1,1].set_aspect('equal') ax[1,1].set_title('Pixel Axises Histogram') divider = make_axes_locatable(ax[1,1]) axHistx = divider.append_axes("top", 1.2, pad=0.1, sharex=ax[1,1]) axHisty = divider.append_axes("right", 1.2, pad=0.1, sharey=ax[1,1]) # make some labels invisible plt.setp(axHistx.get_xticklabels() + axHisty.get_yticklabels(),visible=False) # now determine nice limits by hand: axHistx.hist(index[1], bins=bx) axHistx.axhline(y=th_y*np.mean(hy),c="red",linewidth=2,zorder=0) axHisty.hist(index[0], bins=by, orientation='horizontal') axHisty.axvline(x=th_x*np.mean(hx),c="red",linewidth=2,zorder=0) #axHistx.axis["bottom"].major_ticklabels.set_visible(False) for tl in axHistx.get_xticklabels(): tl.set_visible(False) axHistx.set_yticks([0, 400, 800, 1200]) #axHisty.axis["left"].major_ticklabels.set_visible(False) for tl in axHisty.get_yticklabels(): tl.set_visible(False) axHisty.set_xticks([0, 400, 800, 1200]) ax[1,2].imshow(interest_image,cmap=plt.cm.gray) ax[1,2].set_title('Edge Detection') plt.show() #""" return [interest_image,[bottom,top,left,right],rotate_angle*180]
def main(): if len(sys.argv) != 2: print "ERROR! Correct usage is:" print "\tpython test_hough_transform.py [gps_point_collection.dat]" return GRID_SIZE = 500 results = np.zeros((GRID_SIZE, GRID_SIZE), np.float) # Load GPS points with open(sys.argv[1], "rb") as fin: point_collection = cPickle.load(fin) for pt in point_collection: y_ind = math.floor((pt[0] - const.RANGE_SW[0]) / (const.RANGE_NE[0] -const.RANGE_SW[0]) * GRID_SIZE) x_ind = math.floor((pt[1] - const.RANGE_NE[1]) / (const.RANGE_SW[1] -const.RANGE_NE[1]) * GRID_SIZE) results[x_ind, y_ind] += 1.0 if results[x_ind, y_ind] >= 64: results[x_ind, y_ind] = 63 results /= np.amax(results) thresholded_results = np.zeros((GRID_SIZE, GRID_SIZE), np.bool) THRESHOLD = 0.02 for i in range(0, GRID_SIZE): for j in range(0, GRID_SIZE): if results[i,j] >= THRESHOLD: thresholded_results[i,j] = 1 else: thresholded_results[i,j] = 0 box_size = 50 x_ind = random.randint(box_size, GRID_SIZE-box_size) y_ind = random.randint(box_size, GRID_SIZE-box_size) # x_ind = 217 # y_ind = 175 test_img = thresholded_results[(x_ind-box_size):(x_ind+box_size),\ (y_ind-box_size):(y_ind+box_size)] h, theta, d = hough_line(test_img) # fig = plt.figure(figsize=(30,16)) # ax = fig.add_subplot(121, aspect='equal') # ax.imshow(test_img, cmap=plt.cm.gray) # # ax = fig.add_subplot(122) # img = skeletonize(test_img) # ax.imshow(img, cmap=plt.cm.gray) # plt.show() # fig = plt.figure(figsize=(30,16)) # ax = fig.add_subplot(131, aspect='equal') # ax.imshow(test_img, cmap=plt.cm.gray) # # ax = fig.add_subplot(132) # ax.imshow(np.log(1+h), # extent=[np.rad2deg(theta[-1]), np.rad2deg(theta[0]), d[-1], d[0]], # cmap=plt.cm.gray, aspect=1/1.5) # ax = fig.add_subplot(133) # ax.imshow(test_img, cmap=plt.cm.gray) # rows, cols = test_img.shape # for _, angle, dist in zip(*hough_line_peaks(h, theta, d)): # y0 = (dist - 0 * np.cos(angle)) / np.sin(angle) # y1 = (dist - cols * np.cos(angle)) / np.sin(angle) # ax.plot((0, cols), (y0, y1), '-r') # ax.set_xlim([0, cols]) # ax.set_ylim([rows, 0]) # plt.show() print "point at: ", x_ind, y_ind coords = [(y_ind-box_size, x_ind-box_size), (y_ind+box_size, x_ind-box_size),\ (y_ind+box_size, x_ind+box_size), (y_ind-box_size, x_ind+box_size), \ (y_ind-box_size, x_ind-box_size)] bound_box = Polygon(coords) patch = PolygonPatch(bound_box, fc='none', ec='red') fig = plt.figure(figsize=(30,16)) rows, cols = thresholded_results.shape ax = fig.add_subplot(121, aspect='equal') ax.imshow(thresholded_results, cmap=plt.cm.gray) ax.add_patch(patch) ax.set_xlim([0, cols]) ax.set_ylim([rows, 0]) ax = fig.add_subplot(122) ax.imshow(test_img, cmap=plt.cm.gray) for _, angle, dist in zip(*hough_line_peaks(h, theta, d, min_distance=8)): y0 = (dist - 0 * np.cos(angle)) / np.sin(angle) y1 = (dist - cols * np.cos(angle)) / np.sin(angle) ax.plot((0, cols), (y0, y1), '-r') rows, cols = test_img.shape ax.set_xlim([0, cols]) ax.set_ylim([rows, 0]) plt.show()
from skimage import exposure, feature import numpy as np import matplotlib.pyplot as plt # Chargement ou construction d'une image image = data.checkerboard() # image = np.zeros((200, 200)) # image[40:160, 40:160] = 255 # image[70:130, 70:130] = 0 # Détection des contours edges = feature.canny(image, 2, 1, 25) # Calcul de la transformée de Hough h, theta, d = hough_line(edges, theta=np.linspace(-np.pi, np.pi, 200)) plt.figure() # Affichage de l'image initiale plt.subplot(221) plt.imshow(image) plt.title('Image initiale') # Affichage des contours plt.gray() plt.subplot(222) plt.imshow(edges) plt.title('Contours') # Affichage de la transformée de Hough
def lines(base, test): """ Reads two images of yoga poses and compares them. """ image1 = imread(base, flatten=True) image2 = imread(test, flatten=True) # Angles a1 = [] a2 = [] group1_a1 = [] group2_a1 = [] group3_a1 = [] # Generate figure and 2 axes from matplotlib fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4)) # # Plot 1 -> Base Case (original) # print "Plot 1" h, theta, d = hough_line(image1) ax1.imshow(image1, cmap=plt.cm.get_cmap('gray')) rows, cols = image1.shape for _, angle, dist in zip(*hough_line_peaks(h, theta, d)): y0 = (dist - 0 * np.cos(angle)) / np.sin(angle) y1 = (dist - cols * np.cos(angle)) / np.sin(angle) degree = degrees(angle) a1.append(degree) if degree < -45 or degree > 45: if degree < -85 or degree > 85: pos_horizontal = [] neg_horizontal = [] if degree > 0: pos_horizontal.append(90 - degree) elif degree <= 0: neg_horizontal.append(-(degree + 90)) ax1.plot((0, cols), (y0, y1), '-r') elif degree > -45 and degree < 0: if degree > -40 and degree < -25: group2_a1.append(degree) ax1.plot((0, cols), (y0, y1), '-r') elif degree > 0 and degree < 45: if degree > 15 and degree < 40: group3_a1.append(degree) ax1.plot((0, cols), (y0, y1), '-r') ax1.axis((0, cols, rows, 0)) ax1.set_title('Detected lines') ax1.set_axis_off() if len(pos_horizontal) == 0: avg_horizontal = reduce(lambda x, y: x + y, neg_horizontal) / float(len(neg_horizontal)) elif len(neg_horizontal) == 0: avg_horizontal = reduce(lambda x, y: x + y, pos_horizontal) / float(len(pos_horizontal)) else: avg_neg = reduce(lambda x, y: x + y, neg_horizontal) / float(len(neg_horizontal)) avg_pos = reduce(lambda x, y: x + y, pos_horizontal) / float(len(pos_horizontal)) avg_horizontal = (avg_pos + avg_neg)/2 print "BASE HORIZONTAL: " + str(avg_horizontal) # print group2_a1 # print group3_a1 # Plot 2 -> Test Case (submission) # print "\nPlot 2" h1, theta1, d1 = hough_line(image2) ax2.imshow(image2, cmap=plt.cm.gray) rows, cols = image2.shape group1_a2 = [] group2_a2 = [] group3_a2 = [] for _, angle, dist in zip(*hough_line_peaks(h1, theta1, d1)): y0 = (dist - 0 * np.cos(angle)) / np.sin(angle) y1 = (dist - cols * np.cos(angle)) / np.sin(angle) degree = degrees(angle) a2.append(degree) if degree < -45 or degree > 45: if degree < -85 or degree > 85: pos_horizontal_user = [] neg_horizontal_user = [] if degree > 0: pos_horizontal_user.append(90 - degree) elif degree <= 0: neg_horizontal_user.append(-(degree + 90)) ax2.plot((0, cols), (y0, y1), '-r') elif degree > -45 and degree < 0: if degree > -40 and degree < -25: group2_a2.append(degree) ax2.plot((0, cols), (y0, y1), '-r') elif degree > 0 and degree < 45: if degree > 15 and degree < 40: group3_a2.append(degree) ax2.plot((0, cols), (y0, y1), '-r') a2.append(degrees(angle)) # ax2.plot((0, cols), (y0, y1), '-r') if len(pos_horizontal_user) == 0: avg_horizontal_user = reduce(lambda x, y: x + y, neg_horizontal_user) / float(len(neg_horizontal_user)) elif len(neg_horizontal_user) == 0: avg_horizontal_user = reduce(lambda x, y: x + y, pos_horizontal_user) / float(len(pos_horizontal_user)) else: avg_neg = reduce(lambda x, y: x + y, neg_horizontal_user) / float(len(neg_horizontal_user)) avg_pos = reduce(lambda x, y: x + y, pos_horizontal_user) / float(len(pos_horizontal_user)) avg_horizontal_user = (avg_pos + avg_neg)/2 print "USER HORIZONTAL: " + str(avg_horizontal_user) # print sorted(a2, key=float) # print group2_a2 # print group3_a2 avg_down = -1 avg_up =-1 base_down = reduce(lambda x, y: x + y, group2_a1) / float(len(group2_a1)) if len(group2_a2) > 0: avg_down = reduce(lambda x, y: x + y, group2_a2) / float(len(group2_a2)) base_up = reduce(lambda x, y: x + y, group3_a1) / float(len(group3_a1)) if len(group3_a2) > 0: avg_up = reduce(lambda x, y: x + y, group3_a2) / float(len(group3_a2)) print "BASE DOWN: " + str(base_down) print "USER DOWN: " + str(avg_down) print "BASE UP: " + str(base_up) print "USER UP: " + str(avg_up) ax2.axis((0, cols, rows, 0)) ax2.set_title('Detected lines') ax2.set_axis_off() plt.show() return a1, a2