def test_hough_ellipse_non_zero_angle(): img = np.zeros((20, 20), dtype=int) a = 6 b = 9 x0 = 10 y0 = 10 angle = np.pi / 1.35 rr, cc = ellipse_perimeter(x0, x0, b, a, orientation=angle) img[rr, cc] = 1 result = tf.hough_ellipse(img, threshold=15, accuracy=3) assert_almost_equal(result[0][0] / 100., x0 / 100., decimal=1) assert_almost_equal(result[0][1] / 100., y0 / 100., decimal=1) assert_almost_equal(result[0][2] / 100., b / 100., decimal=1) assert_almost_equal(result[0][3] / 100., a / 100., decimal=1) assert_almost_equal(result[0][4], angle, decimal=1)
def test_hough_ellipse_zero_angle(): img = np.zeros((25, 25), dtype=int) a = 6 b = 8 x0 = 12 y0 = 12 angle = 0 rr, cc = ellipse_perimeter(x0, x0, b, a) img[rr, cc] = 1 result = tf.hough_ellipse(img, threshold=9) assert_equal(result[0][0], x0) assert_equal(result[0][1], y0) assert_almost_equal(result[0][2], b, decimal=1) assert_almost_equal(result[0][3], a, decimal=1) assert_equal(result[0][4], angle)
def test_hough_ellipse_non_zero_negangle4(): # ry < rx, angle in [-pi:-3pi/4] img = np.zeros((30, 24), dtype=int) rx = 12 ry = 6 x0 = 10 y0 = 15 angle = -np.pi / 1.35 - np.pi rr, cc = ellipse_perimeter(y0, x0, ry, rx, orientation=angle) img[rr, cc] = 1 result = tf.hough_ellipse(img, threshold=15, accuracy=3) result.sort(order="accumulator") best = result[-1] # Check if I re-draw the ellipse, points are the same! # ie check API compatibility between hough_ellipse and ellipse_perimeter rr2, cc2 = ellipse_perimeter(y0, x0, int(best[3]), int(best[4]), orientation=best[5]) assert_equal(rr, rr2) assert_equal(cc, cc2)
def extract_hough_ellipse(image_gray): edges = canny(image_gray, sigma=3.0, low_threshold=0.55, high_threshold=0.8) # Perform a Hough Transform # The accuracy corresponds to the bin size of a major axis. # The value is chosen in order to get a single high accumulator. # The threshold eliminates low accumulators print 'hough_ellipse' result = hough_ellipse(edges, accuracy=20, threshold=250, min_size=100, max_size=120) result.sort(order='accumulator') print len(result) # Estimated parameters for the ellipse best = result[-1] yc = int(best[1]) xc = int(best[2]) a = int(best[3]) b = int(best[4]) orientation = best[5]
def main(): # Load picture, convert to grayscale and detect edges camera = cv2.VideoCapture(0) (ret, img) = camera.read() cv2.imshow("blah",img) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) cp = gray.copy() edges = cv2.Canny(gray,50,150,apertureSize = 3) print "hi" edges = img_as_float(edges) print "hi" # Perform a Hough Transform # The accuracy corresponds to the bin size of a major axis. # The value is chosen in order to get a single high accumulator. # The threshold eliminates low accumulators result = hough_ellipse(edges, accuracy=20, threshold=250, min_size=100, max_size=120) print "hi" result.sort(order='accumulator') print result # Estimated parameters for the ellipse if (len(result) > 0): print "apple" best = list(result[-1]) yc, xc, a, b = [int(round(x)) for x in best[1:5]] orientation = best[5] # Draw the ellipse on the original image cy, cx = ellipse_perimeter(yc, xc, a, b, orientation) image_rgb[cy, cx] = (0, 0, 255) # Draw the edge (white) and the resulting ellipse (red) edges = color.gray2rgb(edges) edges[cy, cx] = (25, 0, 255) # fig2, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(8, 4), sharex=True, # sharey=True, # subplot_kw={'adjustable':'box-forced'}) # ax1.set_title('Original picture') cv2.imshow("apple",img_as_ubyte(edges))
def test_hough_ellipse_zero_angle(): img = np.zeros((25, 25), dtype=int) rx = 6 ry = 8 x0 = 12 y0 = 15 angle = 0 rr, cc = ellipse_perimeter(y0, x0, ry, rx) img[rr, cc] = 1 result = tf.hough_ellipse(img, threshold=9) best = result[-1] assert_equal(best[1], y0) assert_equal(best[2], x0) assert_almost_equal(best[3], ry, decimal=1) assert_almost_equal(best[4], rx, decimal=1) assert_equal(best[5], angle) # Check if I re-draw the ellipse, points are the same! # ie check API compatibility between hough_ellipse and ellipse_perimeter rr2, cc2 = ellipse_perimeter(y0, x0, int(best[3]), int(best[4]), orientation=best[5]) assert_equal(rr, rr2) assert_equal(cc, cc2)
def test(imgs): detected = 0 Non_detected = 0 for img in imgs: print(detected, Non_detected) path = img image_rgb = cv2.imread(path, cv2.IMREAD_COLOR) image_gray = cv2.imread(path, cv2.IMREAD_GRAYSCALE) _, image_bin = cv2.threshold(image_gray, 0, 255, cv2.THRESH_OTSU) edges = canny(image_bin, sigma=2.0, low_threshold=0.25, high_threshold=0.8) try: result = hough_ellipse(edges, accuracy=9, threshold=52, min_size=20) result.sort(order='accumulator') # Estimated parameters for the ellipse best = list(result[-1]) yc, xc, a, b = [int(round(x)) for x in best[1:5]] orientation = best[5] # Draw the ellipse on the original image cy, cx = ellipse_perimeter(yc, xc, a, b, orientation) image_rgb[cy, cx] = (0, 0, 255) # Draw the edge (white) and the resulting ellipse (red) edges = color.gray2rgb(img_as_ubyte(edges)) edges[cy, cx] = (250, 0, 0) detected += 1 except: Non_detected += 1 return (detected, Non_detected)
def test_hough_ellipse_non_zero_negangle4(): # ry < rx, angle in [-pi:-3pi/4] img = np.zeros((30, 24), dtype=int) rx = 12 ry = 6 x0 = 10 y0 = 15 angle = -np.pi / 1.35 - np.pi rr, cc = ellipse_perimeter(y0, x0, ry, rx, orientation=angle) img[rr, cc] = 1 result = transform.hough_ellipse(img, threshold=15, accuracy=3) result.sort(order='accumulator') best = result[-1] # Check if I re-draw the ellipse, points are the same! # ie check API compatibility between hough_ellipse and ellipse_perimeter rr2, cc2 = ellipse_perimeter(y0, x0, int(best[3]), int(best[4]), orientation=best[5]) assert_equal(rr, rr2) assert_equal(cc, cc2)
def test_hough_ellipse_non_zero_posangle2(): # ry < rx, angle in [0:pi/2] img = np.zeros((30, 24), dtype=int) rx = 12 ry = 6 x0 = 10 y0 = 15 angle = np.pi / 1.35 rr, cc = ellipse_perimeter(y0, x0, ry, rx, orientation=angle) img[rr, cc] = 1 result = tf.hough_ellipse(img, threshold=15, accuracy=3) result.sort(order="accumulator") best = result[-1] assert_almost_equal(best[1] / 100.0, y0 / 100.0, decimal=1) assert_almost_equal(best[2] / 100.0, x0 / 100.0, decimal=1) assert_almost_equal(best[3] / 10.0, ry / 10.0, decimal=1) assert_almost_equal(best[4] / 100.0, rx / 100.0, decimal=1) assert_almost_equal(best[5], angle, decimal=1) # Check if I re-draw the ellipse, points are the same! # ie check API compatibility between hough_ellipse and ellipse_perimeter rr2, cc2 = ellipse_perimeter(y0, x0, int(best[3]), int(best[4]), orientation=best[5]) assert_equal(rr, rr2) assert_equal(cc, cc2)
def find_circle(image, x_start, y_start, mask=False): # pre-processing # 사전 작업 image = rgb2gray(image) if mask: mask = image > 0.1 image[mask] = 1 image = canny(image, sigma=1.75, low_threshold=0.55, high_threshold=0.8) # Perform a hough Transform # The accuracy corresponds to the bin size of a major axis. # The value is chosen in order to get a single high accumulator. # The threshold eliminates low accumulators # 허프 변환 수행 # 정확도는 장축의 크기에 따라 달라집니다 # 하나의 높은 값을 얻기 위한 계산이며 # 임계값은 낮은 정확도의 값을 제거 합니다. result = hough_ellipse(image) result.sort(order='accumulator') # Estimated parameters for the ellipse best = list(result[-1]) xc, yc, a, b = [int(round(x)) for x in best[1:5]] return yc + y_start, xc + x_start
def test_canny(): data = np.memmap("E:\\guts_tracking\\data\\fish202_aligned_masked_8bit_150x200x440.raw", dtype='uint8', shape=(440,200,150)).copy() data_slice = data[150] sigmas = np.linspace(1,5,5) low_thresholds = np.linspace(0.1,0.55,5) thresholds = np.linspace(5,10,5) accuracies = np.linspace(5,25,5) edges = feature.canny(data_slice, sigma=3.0, low_threshold=0.4, high_threshold=0.8) ellipses = hough_ellipse(edges, threshold=4, accuracy=1, min_size=15, max_size=300) print ellipses ellipses.sort(order='accumulator') new_slice = draw_esllipse(edges, ellipses) plt.imshow(new_slice, cmap='gray') #fig, axes = plt.subplots(5, 5) #for i,sigma in enumerate(sigmas): #for j,low_threshold in enumerate(low_thresholds): # for i,threshold in enumerate(thresholds): # for j,accuracy in enumerate(accuracies): # edges = feature.canny(data_slice, sigma=3.0, low_threshold=0.4, high_threshold=0.8) # ellipses = hough_ellipse(edges, threshold=threshold, accuracy=accuracy, min_size=15, max_size=300) # ellipses.sort(order='accumulator') # new_slice = draw_esllipse(data_slice, ellipses) # # axes[i,j].imshow(new_slice, cmap='gray') # #axes[i,j].set_title('sigma=%f, low_th=%f' % (sigma, low_threshold)) # axes[i,j].set_title('threshold=%f, accuracy=%f' % (threshold, accuracy)) # axes[i,j].get_xaxis().set_visible(False) # axes[i,j].get_yaxis().set_visible(False) plt.show()
def test_hough_ellipse_non_zero_posangle2(): # ry < rx, angle in [0:pi/2] img = np.zeros((30, 24), dtype=int) rx = 12 ry = 6 x0 = 10 y0 = 15 angle = np.pi / 1.35 rr, cc = ellipse_perimeter(y0, x0, ry, rx, orientation=angle) img[rr, cc] = 1 result = tf.hough_ellipse(img, threshold=15, accuracy=3) result.sort(order='accumulator') best = result[-1] assert_almost_equal(best[1] / 100., y0 / 100., decimal=1) assert_almost_equal(best[2] / 100., x0 / 100., decimal=1) assert_almost_equal(best[3] / 10., ry / 10., decimal=1) assert_almost_equal(best[4] / 100., rx / 100., decimal=1) assert_almost_equal(best[5], angle, decimal=1) # Check if I re-draw the ellipse, points are the same! # ie check API compatibility between hough_ellipse and ellipse_perimeter rr2, cc2 = ellipse_perimeter(y0, x0, int(best[3]), int(best[4]), orientation=best[5]) assert_equal(rr, rr2) assert_equal(cc, cc2)
def ellipseDetect(input): edges,_ = input result = hough_ellipse(edges,accuracy=1,threshold=2,min_size=5,max_size=20) result.sort(order='accumulator') result = [x for x in result if x[4]>2 and x[3]>2] # must be non-degenerate result = [x for x in result if abs(x[4]/x[3]-1.0)<0.2] # nearly circular best = result[-100:] img = edges.astype(np.ubyte)*255 # merge together into a 3 channel grayscale img = cv.merge([img,img,img]) # show results for e in best: ee = list(e) yc, xc, a, b = [int(round(x)) for x in ee[1:5]] orientation = ee[5] # draw ellipse cy, cx = ellipse_perimeter(yc, xc, a, b, orientation) cx = np.clip(cx,0,99) cy = np.clip(cy,0,99) img[cy, cx] = (255, 0, 0) return img
edge_minth = 0.03 edge_maxth = 0.3 edge_sigma = 1.0 edges = canny(img, edge_sigma, edge_maxth, edge_minth) #plt.imshow(edges) #plt.show() # Ellipse detection minMajorAxis = 35 maxMinorAxis = 110 result = hough_ellipse(edges, accuracy=10, threshold=100, min_size=minMajorAxis, max_size=maxMinorAxis) result.sort(order='accumulator') result = result[::-1] #best = list(result[-1]) #yc, xc, a, b = [int(round(x)) for x in best[1:5]] #orientation = best[5] #cy, cx = ellipse_perimeter(yc, xc, a, b, orientation) #pdb.set_trace() #img_color[cy, cx] = (0, 0, 255) #plt.show()
def Hough_check(imgfile, style=0): """ 霍夫变换算法可以快速、准确的检测出图片中的直线、圆和椭圆等多种形状 :param imgfile: :param style:0-直线,1-圆,2-椭圆 :return: """ img = cv2.imread(imgfile) # 读取图片 output = img.copy() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 彩色图片灰度化 edges = cv2.Canny(gray, 100, 200) # 执行边缘检测 # 显示原始结果 # cv2.imwrite('edges.png', edges) cv2.imshow('edge', edges) if style == 0: # 执行Hough直线检测 lines = cv2.HoughLines(edges, 1, np.pi / 180, 160) if lines is None: print("no lines") return lines1 = lines[:, 0, :] for rho, theta in lines1: 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, (x1, y1), (x2, y2), (255, 0, 0), 1) # cv2.imwrite('line.png', img) cv2.imshow('line', img) elif style == 1: gaussian = cv2.GaussianBlur(gray, (3, 3), 0) circles1 = cv2.HoughCircles(gaussian, cv2.HOUGH_GRADIENT, 1, 100, param1=100, param2=30, minRadius=15, maxRadius=80) print(np.shape(circles1)) # hough_gradient 霍夫梯度法 circles = circles1[0, :, :] circles = np.uint16(np.around(circles)) for i in circles[:]: cv2.circle(img, (i[0], i[1]), i[2], (0, 255, 0), 3) cv2.circle(img, (i[0], i[1]), 2, (255, 0, 255), 10) cv2.imshow('img', img) # 应用hough变换进行圆检测 # circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 100) # # 确保至少发现一个圆 # if circles is None: # print("no circles") # return # # # 进行取整操作 # circles = np.round(circles[0, :]).astype("int") # # 循环遍历所有的坐标和半径 # for (x, y, r) in circles: # # 绘制结果 # cv2.circle(output, (x, y), r, (0, 255, 0), 4) # cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1) # # cv2.imshow("output", np.hstack([img, output])) # 显示结果 elif style == 2: # 加载图片,转换成灰度图并检测边缘 image_rgb = data.coffee()[0:220, 160:420] # 裁剪原图像,不然速度非常慢 image_gray = color.rgb2gray(image_rgb) edges = feature.canny(image_gray, sigma=2.0, low_threshold=0.55, high_threshold=0.8) # 执行椭圆变换 result = transform.hough_ellipse(edges, accuracy=20, threshold=250, min_size=100, max_size=120) result.sort(order='accumulator') # 根据累加器排序 # 估计椭圆参数 best = list(result[-1]) # 排完序后取最后一个 yc, xc, a, b = [int(round(x)) for x in best[1:5]] orientation = best[5] # 在原图上画出椭圆 cy, cx = draw.ellipse_perimeter(yc, xc, a, b, orientation) image_rgb[cy, cx] = (0, 0, 255) # 在原图中用蓝色表示检测出的椭圆 # #分别用白色表示canny边缘,用红色表示检测出的椭圆,进行对比 # edges = color.gray2rgb(edges) # edges[cy, cx] = (250, 0, 0) fig2, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(8, 4)) ax1.set_title('Original picture') ax1.imshow(image_rgb) ax2.set_title('Detect result') ax2.imshow(edges) plt.show() cv2.waitKey(0) cv2.destroyAllWindows()
circles = cv2.HoughCircles(dilate1, cv2.HOUGH_GRADIENT, 1, 120, param1=100, param2=10, minRadius=10, maxRadius=50) circles = np.uint16(np.around(circles)) print(circles) for i in circles[0, :]: print('i', i[2]) # draw the outer circle cv2.circle(planets, (i[0], i[1]), i[2], (0, 255, 0), 2) # draw the center of the circle cv2.circle(planets, (i[0], i[1]), 2, (0, 0, 255), 3) cv2.imwrite("planets_circles.jpg", planets) cv2.imshow("HoughCirlces", planets) cv2.waitKey(0) cv2.destroyAllWindows() result = transform.hough_ellipse(dilate, accuracy=20, threshold=250, min_size=50, max_size=30) #result.sort(order='accumulator') # 根据累加器排序 print(result)
img2[circy, circx] = (220, 200, 200) ax.imshow(img2, cmap=plt.cm.gray) plt.show() # Perform a Hough Transform # The accuracy corresponds to the bin size of a major axis. # The value is chosen in order to get a single high accumulator. # The threshold eliminates low accumulators from skimage import data, color, img_as_ubyte from skimage.transform import hough_ellipse from skimage.draw import ellipse_perimeter result = hough_ellipse(edge2, accuracy=20, threshold=300, min_size=50, max_size=200) result.sort(order='accumulator') # Estimated parameters for the ellipse best = list(result[0]) yc, xc, a, b = [int(round(x)) for x in best[1:5]] #orientation = best[5] orientation = 85 yc = 110 xc = 130 b = 55 a = 30 # Draw the ellipse on the original image
def process_wrapper(self, **kwargs): wrapper = self.init_wrapper(**kwargs) if wrapper is None: return False res = False try: # Read params input_kind = self.get_value_of("source_selector") edge_only = self.get_value_of("edge_only") == 1 roi = self.get_ipt_roi( wrapper=wrapper, roi_names=[self.get_value_of("crop_roi_name")], selection_mode="all_named", ) roi = roi[0] if roi else None if input_kind == "mask": img = self.get_mask() elif input_kind == "current_image": img = wrapper.current_image else: img = None logger.error(f"Unknown source: {input_kind}") self.result = None return pkl_file = os.path.join( ipso_folders.get_path("stored_data"), self.get_short_hash(exclude_list=()) + ".pkl", ) if ( (self.get_value_of("enable_cache") == 1) and edge_only is False and os.path.isfile(pkl_file) ): with open(pkl_file, "rb") as f: result = pickle.load(f) else: # Get the edge with IptEdgeDetector(wrapper=wrapper, **self.params_to_dict()) as ( res, ed, ): if not res: return edges = ed.result if edge_only is True: self.result = ed.result self.demo_image = self.result return True result = hough_ellipse( edges, accuracy=self.get_value_of("hough_accuracy"), threshold=self.get_value_of("hough_threshold"), min_size=self.get_value_of("min_radius"), max_size=self.get_value_of("max_radius"), ) result.sort(order="accumulator") if self.get_value_of("enable_cache") == 1: with open(pkl_file, "wb") as f: pickle.dump(result, f) if result is not None: colors = ipc.build_color_steps(step_count=len(result)) for i, ellipse in enumerate(result): yc, xc, a, b = [int(round(x)) for x in ellipse[1:5]] orientation = ellipse[5] cy, cx = ellipse_perimeter(yc, xc, a, b, orientation) img[cy, cx] = colors[i] wrapper.store_image(image=img, text="hough_ellipses") self.demo_image = img res = True except Exception as e: logger.exception(f'Failed to process {self. name}: "{repr(e)}"') res = False else: pass finally: return res
print('Detecting Edges') edges = canny(image_rgb) # , sigma=2.0, low_threshold=0.55, high_threshold=0.8) plt.imshow(edges) plt.show() # Perform a Hough Transform # The accuracy corresponds to the bin size of a major axis. # The value is chosen in order to get a single high accumulator. # The threshold eliminates low accumulators # plt.imshow(edges) # plt.show() print('Performing Hough Transform') result = hough_ellipse(edges, min_size=70) # accuracy=20, threshold=250, # min_size=100, max_size=120) print('Sorting result') result.sort(order='accumulator') # Estimated parameters for the ellipse best = list(result[-1]) yc, xc, a, b = [int(round(x)) for x in best[1:5]] orientation = best[5] print('Found Ellipse Parameters') # Draw the ellipse on the original image cy, cx = ellipse_perimeter(yc, xc, a, b, orientation) print('Finding Ellipse Perimeter') image_rgb[cy, cx] = (0, 0, 255) # Draw the edge (white) and the resulting ellipse (red)
from skimage.transform import hough_ellipse from skimage.draw import ellipse_perimeter # Load picture, convert to grayscale and detect edges image_rgb = data.load('coffee.png')[0:220, 100:450] image_gray = color.rgb2gray(image_rgb) edges = filter.canny(image_gray, sigma=2.0, low_threshold=0.55, high_threshold=0.8) # Perform a Hough Transform # The accuracy corresponds to the bin size of a major axis. # The value is chosen in order to get a single high accumulator. # The threshold eliminates low accumulators accum = hough_ellipse(edges, accuracy=10, threshold=170, min_size=50) accum.sort(key=lambda x: x[5]) # Estimated parameters for the ellipse center_y = int(accum[-1][0]) center_x = int(accum[-1][1]) xradius = int(accum[-1][2]) yradius = int(accum[-1][3]) angle = np.pi - accum[-1][4] # Draw the ellipse on the original image cx, cy = ellipse_perimeter(center_y, center_x, yradius, xradius, orientation=angle) image_rgb[cy, cx] = (0, 0, 1)
# ax2.set_title('gray') # ax2.imshow(image_gray) # ax3 = plt.subplot(1,3,3) # ax3.set_title('Edge (white) and result (red)') # ax3.imshow(edges) # plt.show() # sleep(1) # Perform a Hough Transform # The accuracy corresponds to the bin size of a major axis. # The value is chosen in order to get a single high accumulator. # The threshold eliminates low accumulators try: result = hough_ellipse(edges, accuracy=9.6, threshold=55, min_size=20) print(result) # sleep(10) result.sort(order='accumulator') # Estimated parameters for the ellipse best = list(result[-1]) yc, xc, a, b = [int(round(x)) for x in best[1:5]] orientation = best[5] # Draw the ellipse on the original image cy, cx = ellipse_perimeter(yc, xc, a, b, orientation) image_rgb[cy, cx] = (0, 0, 255) # Draw the edge (white) and the resulting ellipse (red) edges = color.gray2rgb(img_as_ubyte(edges))
from skimage import data, filter, color from skimage.transform import hough_ellipse from skimage.draw import ellipse_perimeter # Load picture, convert to grayscale and detect edges image_rgb = data.load('coffee.png')[0:220, 100:450] image_gray = color.rgb2gray(image_rgb) edges = filter.canny(image_gray, sigma=2.0, low_threshold=0.55, high_threshold=0.8) # Perform a Hough Transform # The accuracy corresponds to the bin size of a major axis. # The value is chosen in order to get a single high accumulator. # The threshold eliminates low accumulators accum = hough_ellipse(edges, accuracy=10, threshold=170, min_size=50) accum.sort(key=lambda x:x[5]) # Estimated parameters for the ellipse center_y = int(accum[-1][0]) center_x = int(accum[-1][1]) xradius = int(accum[-1][2]) yradius = int(accum[-1][3]) angle = np.pi - accum[-1][4] # Draw the ellipse on the original image cx, cy = ellipse_perimeter(center_y, center_x, yradius, xradius, orientation=angle) image_rgb[cy, cx] = (0, 0, 1) # Draw the edge (white) and the resulting ellipse (red) edges = color.gray2rgb(edges) edges[cy, cx] = (250, 0, 0)
ret, frame = vid.read() img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) plt.imshow(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 100, param1=100, param2=50, minRadius=30, maxRadius=500) edges = canny(img, sigma=3.0) for edge in edges: plt.plot(edge[1], edge[0], linewidth=2) plt.imshow(edges, cmap='gray') plt.show() print(edges) print("pries elipses") ellipses = hough_ellipse(edges, accuracy=20, threshold=500, min_size=50, max_size=200) print("po elipsiu") if circles is not None: for x, y, r in circles[0]: c = plt.Circle((x, y), r, fill=False, lw=3, ec='C1') plt.gca().add_patch(c) if ellipses is not None: for x, y, r in ellipses[0]: c = plt.Ellipse((x, y), r, fill=False, lw=3, ec='C1') plt.gca().add_patch(c) plt.gcf().set_size_inches((12, 8)) plt.show()
def test_hough_ellipse_all_black_img(): assert(transform.hough_ellipse(np.zeros((100, 100))).shape == (0, 6))
# -*- coding: utf-8 -*- """ Created on Sat Jul 13 18:10:57 2019 @author: mvoulana """ from skimage.transform import hough_ellipse from skimage.draw import ellipse_perimeter import matplotlib.pyplot as plt img = np.zeros((25, 25), dtype=np.uint8) rr, cc = ellipse_perimeter(10, 10, 6, 8) img[cc, rr] = 1 plt.imshow(img) plt.show() result = hough_ellipse(img, threshold=8) result.tolist()
""" """----------------------- Elliptic Hough transform---------------------""" # Perform a Hough Transform # The accuracy corresponds to the bin size of a major axis. # The value is chosen in order to get a single high accumulator. # The threshold eliminates low accumulators #result = hough_ellipse(edges) #result = hough_ellipse(edges, threshold=50) #result = hough_ellipse(edges, accuracy=256) ret, th = cv2.threshold(image_gray, 140, 255, 0) plt.imshow(th) plt.show() result = hough_ellipse(edges, min_size=100, max_size=120) print('4') #result.sort(order='accumulator') """ # Estimated parameters for the ellipse best = list(result[-1]) yc, xc, a, b = [int(round(x)) for x in best[1:5]] orientation = best[5] # Draw the ellipse on the original image cy, cx = ellipse_perimeter(yc, xc, a, b, orientation) image_rgb[cy, cx] = (0, 0, 255) # Draw the edge (white) and the resulting ellipse (red) edges = color.gray2rgb(img_as_ubyte(edges)) edges[cy, cx] = (250, 0, 0)
p0, p1 = line ax3.plot(( p0[0], p1[0] ), ( p0[1], p1[1] )) ax3.set_xlim(( 0, img.shape[1] )) ax3.set_ylim(( img.shape[0], 0 )) ax3.set_title( 'Probabilistic Hough' ) fig.tight_layout() plt.show() # detect circles image_rgb = imm[0] image_gray = color.rgb2gray(image_rgb) edges = feature.canny(image_gray, sigma=2.0, low_threshold=0.55, high_threshold=0.8) # using ellipse transformation result =transform.hough_ellipse(edges,accuracy = 20,threshold=30,min_size=20, max_size=50) result.sort(order='accumulator') # sort by accumulator # get the parameters for ellipse, center and radiuses. best = list(result[-1]) yc, xc, a, b = [int(round(x)) for x in best[1:5]] orientation = best[5] # draw the detected ellipse cy,cx = draw.ellipse_perimeter(yc, xc, a, b, orientation) image_rgb[cy, cx] = (0, 0, 255) plt.imshow(image_rgb) plt.show()
from skimage import io from skimage import data, color from skimage.feature import canny from skimage.transform import hough_ellipse image_rgb = io.imread('coffee.png', 0) image_gray = color.rgb2gray(image_rgb) edges = canny(image_gray, low_threshold=.4, high_threshold=.9) result = hough_ellipse(edges, threshold=20, min_size=10) result.sort(order='accumulator') # Estimated parameters for the ellipse best = list(result[-1]) yc, xc, a, b = [int(round(x)) for x in best[1:5]] orientation = best[5] # Draw the ellipse on the original image cy, cx = ellipse_perimeter(yc, xc, a, b, orientation) image_rgb[cy, cx] = (0, 0, 255) # Draw the edge (white) and the resulting ellipse (red) edges = color.gray2rgb(img_as_ubyte(edges)) edges[cy, cx] = (250, 0, 0) fig2, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(8, 4), sharex=True, sharey=True,
def test_hough_ellipse_all_black_img(): assert (transform.hough_ellipse(np.zeros((100, 100))).shape == (0, 6))
J = [] for i in range(circle_list.shape[0]): P = I[ys[i]:ye[i], xs[i]:xe[i], :] P = np.pad(P, ((pt[i],pb[i]),(pl[i],pr[i]),(0,0)),mode='constant') P = cv2.resize(P, (256,256),interpolation=cv2.INTER_CUBIC) J += [P] return J patches = GetCrops(I, circle_list) for j, J in enumerate(patches): cv2.imwrite('patches_%d.png'%(j), J) continue Y = cv2.cvtColor(J, cv2.COLOR_BGR2GRAY) M = canny(Y, sigma=1.0, low_threshold=10, high_threshold=20) # M = sobel(Y) # M[M < (M.max() / 10)] = 0 plt.imshow(M) plt.waitforbuttonpress() result = hough_ellipse(M, accuracy=1000, threshold=250,min_size=49, max_size=51) result.sort(order='accumulator') plt.imshow(J[:, :, ::-1]) ellipse = Ellipse(xy=rect[0], width=rect[1][0], height=rect[1][1], angle=rect[2], color='r', fill=False) plt.gca().add_artist(ellipse) plt.waitforbuttonpress() plt.clf() dummy = 0
image_gray = cv2.cvtColor(image_rgb, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(image_gray, 1.3, 5) """ for (x,y,w,h) in faces: center = (x + w//2, y + h//2) #3.5 0.55 0.8 minRadius=int((w//2-10)*0.3) maxRadius=int((w//2+10)*0.3) """ edges = canny(image_gray, sigma=2, low_threshold=0.55, high_threshold=0.8) #3.5,3.3,6 #20 50 print("starting Hough ellipse detection....") ximg = rescale(edges, 0.3, multichannel=True) result = hough_ellipse(ximg, accuracy=0, threshold=250, min_size=100, max_size=120) #print(maxRadius,minRadius) """ result = hough_ellipse(ximg,accuracy=45, threshold=10, min_size=70, max_size=180) """ #result.sort(order='accumulator') print("sorted result:", result) print("list size:", result.size) fig2, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(8, 4), sharex=True, sharey=True) ax1.set_title('Original picture')
def get_ellipses(data): edges = feature.canny(data, sigma=3.0, low_threshold=0.55, high_threshold=0.8) result = hough_ellipse(edges, threshold=4, accuracy=5, min_size=20, max_size=300) result.sort(order='accumulator') return result
# Load picture, convert to grayscale and detect edges camera = cv2.VideoCapture(0) (ret, img_frame) = camera.read() time.sleep(1) (ret, img_frame) = camera.read() cv2.imshow("other", img_frame) image_rgb = img_as_float(img_frame) image_gray = color.rgb2gray(image_rgb) edges = canny(image_gray, sigma=2.0, low_threshold=0.55, high_threshold=0.8) # Perform a Hough Transform # The accuracy corresponds to the bin size of a major axis. # The value is chosen in order to get a single high accumulator. # The threshold eliminates low accumulators result = hough_ellipse(edges, accuracy=20, threshold=250, min_size=100, max_size=120) result.sort(order='accumulator') # Estimated parameters for the ellipse best = list(result[-1]) yc, xc, a, b = [int(round(x)) for x in best[1:5]] orientation = best[5] # Draw the ellipse on the original image cy, cx = ellipse_perimeter(yc, xc, a, b, orientation) image_rgb[cy, cx] = (0, 0, 255) # Draw the edge (white) and the resulting ellipse (red) edges = color.gray2rgb(edges) edges[cy, cx] = (250, 0, 0) fig2, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(8, 4), sharex=True,
labels = i_contours.ravel()[within_o_contour_mask] relevant_image_pixels = images.ravel()[within_o_contour_mask] relevant_image_pixels = images.ravel()[within_o_contour_mask] # perform thresholding given the threshold predictions = [] for image, mask in zip(images, o_contours): # detect edges using the canny edge detector edges = canny(image, sigma=3, low_threshold=0.2, high_threshold=0.8, use_quantiles=True, mask=mask) # use hough ellipse in order to fit the expected shape result = hough_ellipse(edges, accuracy=4, threshold=1, min_size=10) prediction = np.zeros_like(image, dtype='bool') if len(result) > 0: result.sort(order='accumulator') best = list(result[-1]) yc, xc, a, b = [int(round(x)) for x in best[1:5]] orientation = best[5] print(yc, xc, a, b, orientation) cy, cx = ellipse(yc, xc, a, b, rotation=-orientation) prediction[cy, cx] = True if visualizations: plt.imshow(prediction) plt.show() predictions.append(prediction) # perform evaluation with our i-contour labels
from skimage.feature import canny from skimage.transform import hough_ellipse from skimage.draw import ellipse_perimeter # Load picture, convert to grayscale and detect edges image_rgb = data.coffee()[0:220, 160:420] image_gray = color.rgb2gray(image_rgb) edges = canny(image_gray, sigma=2.0, low_threshold=0.55, high_threshold=0.8) # Perform a Hough Transform # The accuracy corresponds to the bin size of a major axis. # The value is chosen in order to get a single high accumulator. # The threshold eliminates low accumulators result = hough_ellipse(edges, accuracy=20, threshold=250, min_size=100, max_size=120) result.sort(order='accumulator') # Estimated parameters for the ellipse best = list(result[-1]) yc, xc, a, b = [int(round(x)) for x in best[1:5]] orientation = best[5] # Draw the ellipse on the original image cy, cx = ellipse_perimeter(yc, xc, a, b, orientation) image_rgb[cy, cx] = (0, 0, 255) # Draw the edge (white) and the resulting ellipse (red) edges = color.gray2rgb(edges) edges[cy, cx] = (250, 0, 0)
# Load picture, convert to grayscale and detect edges # image_rgb = data.coffee()[0:220, 160:420] image_rgb = im # image_gray = color.rgb2gray(image_rgb) image_gray = image_gray # edges = canny(image_gray, sigma=2.0, low_threshold=0.55, high_threshold=0.8) edges = canny(image_gray, sigma=0.1) # edges = canny(image_gray) plt.imshow(edges) plt.show() # Perform a Hough Transform # The accuracy corresponds to the bin size of a major axis. # The value is chosen in order to get a single high accumulator. # The threshold eliminates low accumulators # result = hough_ellipse(edges, accuracy=20, threshold=250, min_size=10, max_size=20) result = hough_ellipse(edges, threshold=250, min_size=10, max_size=20) result.sort(order='accumulator') # Estimated parameters for the ellipse best = list(result[-1]) yc, xc, a, b = [int(round(x)) for x in best[1:5]] orientation = best[5] # Draw the ellipse on the original image cy, cx = ellipse_perimeter(yc, xc, a, b, orientation) image_rgb[cy, cx] = (0, 0, 255) # Draw the edge (white) and the resulting ellipse (red) edges = color.gray2rgb(edges) edges[cy, cx] = (250, 0, 0) fig2, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, figsize=(8, 4), sharex=True,