def test_prewitt_h_horizontal(): """Horizontal prewitt on an edge should be a horizontal line.""" i, j = np.mgrid[-5:6, -5:6] image = (i >= 0).astype(float) result = filters.prewitt_h(image) # Check if result match transform direction assert (np.all(result[i == 0] == 1)) assert_allclose(result[np.abs(i) > 1], 0, atol=1e-10)
def test_prewitt_h_horizontal(): """Horizontal prewitt on an edge should be a horizontal line.""" i, j = np.mgrid[-5:6, -5:6] image = (i >= 0).astype(float) result = filters.prewitt_h(image) # Fudge the eroded points i[np.abs(j) == 5] = 10000 assert (np.all(result[i == 0] == 1)) assert_allclose(result[np.abs(i) > 1], 0, atol=1e-10)
def prewittk(image_file, path_to_train): im = imread(image_file, as_gray=True) edges_prewitt_horizontal = prewitt_h(im) edges_prewitt_vertical = prewitt_v(im) imsave(image_file[:-4] + '_p.jpg', edges_prewitt_vertical, cmap='gray') base = os.path.basename(image_file) base = base[:-4] + '.txt' shutil.copy2(path_to_train + "/labels/" + base, path_to_train + "/labels/" + base[:-4] + '_p.txt')
def test_hprewitt_horizontal(): """Horizontal prewitt on an edge should be a horizontal line.""" i, j = np.mgrid[-5:6, -5:6] image = (i >= 0).astype(float) result = filters.prewitt_h(image) # Fudge the eroded points i[np.abs(j) == 5] = 10000 assert (np.all(result[i == 0] == 1)) assert_allclose(result[np.abs(i) > 1], 0, atol=1e-10)
def extractingEdgeFeature(self, image, image_name): # calculating horizontal edges using prewitt kernel edges_prewitt_horizontal = prewitt_h(image) edges_prewitt_horizontal = edges_prewitt_horizontal.flatten() # calculating vertical edges using prewitt kernel edges_prewitt_vertical = prewitt_v(image) edges_prewitt_vertical = edges_prewitt_vertical.flatten() self.extracting_edge_horizontal.append((image_name, edges_prewitt_horizontal)) self.extracting_edge_vertical.append((image_name, edges_prewitt_vertical))
def detect_edges(self, operator="sobel_vertical", kernel_size=3, optional_mask=None, **kwargs): """ :param optional_mask: See skimage.filters.scharr_v for details. :param kernel_size: int size to use for edge detection kernels :param operator: One of sobel_vertical, sobel_horizontal,prewitt_horizontal,prewitt_vertical or laplace. :return: Detected edges """ available_operators = [ "sobel_horizontal", "sobel_vertical", "prewitt_horizontal", "prewitt_vertical", "laplace", "roberts_cross_neg", "roberts_horizontal", "scharr_vertical", "scharr_horizontal", "canny", "roberts" ] if operator not in available_operators: raise ValueError(f"Edge detection with {operator} not supported.") kernels = { 'sobel_horizontal': lambda x: cv2.Sobel(x, cv2.CV_64F, 1, 0, ksize=kernel_size), 'sobel_vertical': lambda x: cv2.Sobel(x, cv2.CV_64F, 0, 1, ksize=kernel_size), 'roberts': lambda x: filters.roberts(x, optional_mask), 'roberts_cross_neg': lambda x: ndimage.convolve(x, np.array([[0, -1], [1, 0]])), 'roberts_cross_pos': lambda x: filters.roberts_pos_diag(x, optional_mask), 'laplace': lambda x: cv2.Sobel(x, cv2.CV_64F, 1, 0, ksize=kernel_size), 'prewitt_horizontal': lambda x: filters.prewitt_h(x, optional_mask), 'prewitt_vertical': lambda x: filters.prewitt_v(x, optional_mask), 'scharr_horizontal': lambda x: filters.scharr_h(x, optional_mask), 'scharr_vertical': lambda x: filters.scharr_v(x, optional_mask) } print(f"Detecting edges with the {operator} operator") # denoise and gray if self.color_mode == "gray": denoised = self.smooth(**kwargs) else: denoised = gray_images(self.smooth(**kwargs)) return list(map(kernels[operator], denoised))
def extractSkFeatures(url, asGray): img = getImage_sk(url, asGray) # Get image as_gray=False hor = prewitt_h(img) ver = prewitt_v(img) img = getImage_sk(url, False) # If you wanna use gray-scale image, remove multichannel=True below; otherwise it errors out # resized_img = resize(img, (426, 640)) # Multiplication of 16 (8*2 look at below) #creating hog features fd, hog_image = hog(img, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2), visualize=True, multichannel=True) return hor, ver, fd, hog_image
def my_features(image): """ Implement your own features Args: img - array of shape (H, W, C) Returns: features - array of (H * W, C) """ features = None grayscale = rgb2gray(image) features = prewitt_h(grayscale) return features
def generate_SIFT_Descriptors(img): # gaussian_pyramid = load_pyramid("gaussian_pyramid") # dog_pyramid = load_pyramid("dog_pyramid") gaussian_pyramid = gen_gaussian_pyramid(img) dog_pyramid = gen_dog_pyramid(img) padded_grad_of_gaussian_pyramid_x = [] padded_grad_of_gaussian_pyramid_y = [] for level in gaussian_pyramid: padded_grad_of_gaussian_pyramid_y.append(np.pad(prewitt_h(level), 8)) padded_grad_of_gaussian_pyramid_x.append(np.pad(prewitt_v(level), 8)) filter = gen_2_D_Gaussian(16, 4) extremas = blob_detection(img, dog_pyramid, upscaling=False) sift_list = [] for point in extremas: sift_descriptor = get_sift(padded_grad_of_gaussian_pyramid_x, padded_grad_of_gaussian_pyramid_y, point, filter) sift_list.append(sift_descriptor) return sift_list
def detect_motion_blur(image, ratio=2, band=None): """ Detect if an image is blurry due to movement, and therefore unreliable to analyze. Uses the variance of the prewitt edge detectors in the horizontal and vertical directions. Parameters ---------- image : ndarray rgb or grayscale image. ratio : float Maximum ratio of edge strength variance in x- to y-directions. `threshold=2` means if `x_edge.var()` / `y_edge.var() is > 2 OR < 0.5, the image is flagged as blurry do to movement. band : int Band of image to use for analysis. Unspecified defaults to 0 (R in RGB). Returns ------- bool - does the image meet requirements? """ if band is None: try: analyze = image[:, :, 0].copy() except: analyze = image.copy() pass else: analyze = image[:, :, band] horiz = img_as_ubyte(filters.prewitt_v(analyze)).var() vert = img_as_ubyte(filters.prewitt_h(analyze)).var() test = horiz / vert if test < ratio and test > 1 / ratio: out = True else: out = False return (out)
def detect_motion_blur(image, ratio=2, band=None): """ Detect if an image is blurry due to movement, and therefore unreliable to analyze. Uses the variance of the prewitt edge detectors in the horizontal and vertical directions. Parameters ---------- image : ndarray rgb or grayscale image. ratio : float Maximum ratio of edge strength variance in x- to y-directions. `threshold=2` means if `x_edge.var()` / `y_edge.var() is > 2 OR < 0.5, the image is flagged as blurry do to movement. band : int Band of image to use for analysis. Unspecified defaults to 0 (R in RGB). Returns ------- bool - does the image meet requirements? """ if band is None: try: analyze = image[:, :, 0].copy() except: analyze = image.copy() pass else: analyze = image[:, :, band] horiz = img_as_ubyte(filters.prewitt_v(analyze)).var() vert = img_as_ubyte(filters.prewitt_h(analyze)).var() test = horiz / vert if test < ratio and test > 1/ratio: out = True else: out = False return(out)
def getRegions(img_orig): # sizes = [4, 6, 8, 10] sizes = [4, 8, 12] img_processed = (255 * np.absolute(filters.prewitt_v(img_orig))).astype(np.uint8) img_aux = (255 * np.absolute(filters.prewitt_h(img_orig))).astype(np.uint8) img_processed[img_aux > 10] = 0 regions_of_interest = [] for s in sizes: img_processed = morphology.dilation(img_processed, morphology.square(s)) thresh = filters.threshold_otsu(img_processed) img_processed = img_processed >= thresh labels = measure.label(img_processed) for region in measure.regionprops(labels): minr, minc, maxr, maxc = region.bbox ratio = float(maxr - minr) / float(maxc - minc) area = region.area if area > 1500 and area < 50000 and ratio < 1 and ratio > 0.2: regions_of_interest.append(region) return regions_of_interest
sob = np.hypot(sx, sy) sobint = sob.astype(int) ''' f, axx = plt.subplots(1, 3) axx[1].imshow(sobel_filter_imh, cmap='gray') axx[1].set_title('Sobel filter along X axis') axx[2].imshow(sobel_filter_imv, cmap='gray') axx[2].set_title('Sobel filter along Y axis') axx[0].imshow(sobel_filter_im, cmap='gray') axx[0].set_title('Sobel filter along X and Y axes') plt.show() #Prewitt filtering the image, looks decent for edge detection prewitt_filter_im = fs.prewitt(im) prewitt_filter_imh = fs.prewitt_h(im) prewitt_filter_imv = fs.prewitt_v(im) prewitt_filter_im = mi.toimage(prewitt_filter_im) prewitt_filter_imh = mi.toimage(prewitt_filter_imh) prewitt_filter_imv = mi.toimage(prewitt_filter_imv) ''' #scipy prewitt filter pw0 = filters.prewitt(im, axis=0, mode='reflect') pw1 = filters.prewitt(im, axis=1, mode='reflect') pw0 = mi.toimage(pw0) pw1 = mi.toimage(pw1) ''' #cmap = cm.Greys_r also yields grey scale images f2, axx2 = plt.subplots(1, 3)
pathVFcolageno = '/Users/Gustavo/AnacondaProjects/pythonCode/0_Database/VFDATABASE/Crop6_collagane/' ImgVFmuscle0 = imread(pathVFmuscle + '0000.tif') ImgVFmuscle1 = imread(pathVFmuscle + '0001.tif') ImgVFcolageno0 = imread(pathVFcolageno + 'Image_0000.tif') ImgVFcolageno1 = imread(pathVFcolageno + 'Image_0001.tif') plt.subplot(2, 2, 1), plt.imshow(ImgVFmuscle0, cmap='viridis') plt.subplot(2, 2, 2), plt.imshow(ImgVFmuscle1, cmap='gray') plt.subplot(2, 2, 3), plt.imshow(ImgVFcolageno0, cmap='gray') plt.subplot(2, 2, 4), plt.imshow(ImgVFcolageno1, cmap='gray') edge_sobel = filters.sobel(ImgVFmuscle0) edge_prewit = filters.prewitt(ImgVFmuscle0) edge_prewitt_v = filters.prewitt_v(ImgVFmuscle0) edge_prewitt_h = filters.prewitt_h(ImgVFmuscle0) fig, axes = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True, figsize=(8, 8)) ax = axes.ravel() ax[0].imshow(ImgVFmuscle0, cmap=plt.cm.gray) ax[0].set_title('Original Image') ax[1].imshow(edge_sobel, cmap=plt.cm.gray) ax[1].set_title('Roberts Edge Detection') ax[2].imshow(edge_prewit, cmap=plt.cm.gray)
img = np.sin(x**2 + y**2) imgx = 2 * x * np.cos(x**2 + y**2) imgy = 2 * y * np.cos(x**2 + y**2) def angle(dx, dy): return np.mod(np.arctan2(dy, dx), np.pi) true_angle = angle(imgx, imgy) angle_farid = angle(farid_h(img), farid_v(img)) angle_sobel = angle(sobel_h(img), sobel_v(img)) angle_scharr = angle(scharr_h(img), scharr_v(img)) angle_prewitt = angle(prewitt_h(img), prewitt_v(img)) def diff_angle(angle_1, angle_2): return np.minimum(np.pi - np.abs(angle_1 - angle_2), np.abs(angle_1 - angle_2)) diff_farid = diff_angle(true_angle, angle_farid) diff_sobel = diff_angle(true_angle, angle_sobel) diff_scharr = diff_angle(true_angle, angle_scharr) diff_prewitt = diff_angle(true_angle, angle_prewitt) fig, axes = plt.subplots(nrows=3, ncols=2, sharex=True,
def test_hprewitt_vertical(): """Horizontal prewitt on a vertical edge should be zero.""" i, j = np.mgrid[-5:6, -5:6] image = (j >= 0).astype(float) result = filters.prewitt_h(image) assert_allclose(result, 0, atol=1e-10)
patch_img = img1[i:i + 3, j:j + 3] pval = np.sum(np.multiply(patch_img, prewitt_operatory)) b[i:i + 1, j:j + 1] = abs(pval) c = abs(np.sqrt(a**2 + b**2)) plt.subplot(2, 3, 1) plt.imshow(abs(a), cmap='gray') plt.title('Horizontal Edges') plt.subplot(2, 3, 2) plt.imshow(abs(b), cmap='gray') plt.title('Vertical Edges') plt.subplot(2, 3, 3) plt.imshow(abs(c), cmap='gray') plt.title('Edges') plt.subplot(2, 3, 4) plt.imshow(abs(prewitt_h(img)), cmap='gray') plt.title('Horizontal Edges Fn') plt.subplot(2, 3, 5) plt.imshow(abs(prewitt_v(img)), cmap='gray') plt.title('Vertical Edges Fn') plt.subplot(2, 3, 6) plt.imshow(abs(prewitt(img)), cmap='gray') plt.title('Total Edges Fn') plt.subplots_adjust(hspace=0.35, wspace=0.35) ##Sobel Operator sobel_operatorx = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) sobel_operatory = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]]) a = np.zeros([512, 512]) b = np.zeros([512, 512])
plt.subplot(2,2,2),plt.imshow(ImgVFmuscle1,cmap='gray') plt.subplot(2,2,3),plt.imshow(ImgVFcolageno0,cmap='gray') plt.subplot(2,2,4),plt.imshow(ImgVFcolageno1,cmap='gray') def angle(dx, dy): return np.arctan2(dy, dx) ########## bordes camera man############### from skimage.data import camera image = camera() edge_sobel = filters.sobel(image) edge_prewit= filters.prewitt(image) edge_prewitt_v=filters.prewitt_v(image) edge_prewitt_h=filters.prewitt_h(image) fig, axes = plt.subplots(nrows=2,ncols=3, sharex=True, sharey=True, figsize=(8, 8)) ax = axes.ravel() ax[0].imshow(image, cmap=plt.cm.gray) ax[0].set_title('Original Image') ax[1].imshow(edge_sobel, cmap=plt.cm.gray) ax[1].set_title('Roberts Edge Detection') ax[2].imshow(edge_prewit, cmap=plt.cm.gray) ax[2].set_title('Prewit Edge Detection') ax[3].imshow(edge_prewitt_v, cmap=plt.cm.gray)
def test_prewitt_h_vertical(): """Horizontal prewitt on a vertical edge should be zero.""" i, j = np.mgrid[-5:6, -5:6] image = (j >= 0).astype(float) result = filters.prewitt_h(image) assert_allclose(result, 0, atol=1e-10)
def test_prewitt_h_zeros(): """Horizontal prewitt on an array of all zeros.""" result = filters.prewitt_h(np.zeros((10, 10)), np.ones((10, 10), dtype=bool)) assert_allclose(result, 0)
def prewitt_H(filename): img = asarray(Image.open(filename)) img = rgb2gray(img) img = filters.prewitt_h(img) plt.imsave(filename, img, cmap="gray") return filename
from skimage import filters from skimage import feature img = io.imread('data/cloud.jpg') plt.imshow(img) img_gray = skimage.color.rgb2gray(img) plt.imshow(img_gray, plt.cm.gray) #平滑滤波 img_e = filters.gaussian(img, sigma=5) plt.imshow(img_e) #robert 算子滤波 img_e = filters.roberts(img_gray) plt.imshow(img_e) #prewitt算子 #水平算子 img_e1 = filters.prewitt_h(img_gray) #垂直算子 img_e2 = filters.prewitt_v(img_gray) #结果(分块绘图) plt.figure('prewitt', figsize=(8, 8)) plt.subplot(121) plt.imshow(img_e1) plt.subplot(122) plt.imshow(img_e2) plt.show() #直接调用 img_e3 = filters.prewitt(img_gray) plt.imshow(img_e3)
from skimage import io from skimage.data import camera from skimage.filters import roberts, sobel, sobel_h, sobel_v, scharr, \ scharr_h, scharr_v, prewitt, prewitt_v, prewitt_h, farid_v, farid_h, laplace, gaussian, prewitt img = io.imread("test_image.jpg"); image = img[:,:,0]; # Roberts Edge Detection edge_roberts = roberts(image); # Laplace of Gaussiann(LOG) Edge Detectipn edge_LOG = laplace(gaussian(image)); # Horizontal Prewitt edge_prewitt_h = prewitt_h(image); # Vertical Prewitt edge_prewitt_v = prewitt_v(image); # Prewitt Edge Detection edge_prewitt = prewitt(image); # Plot Images fig, ax = plt.subplots(ncols=6, sharex=True, sharey=True, figsize=(12, 6)) ax[0].imshow(img, cmap=plt.cm.gray)
def PrewittH(image): image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) return fil.prewitt_h(image)
Different kernels are available to do such operations. The above can be acheieved using Prewitt kernel. i.e. -1 0 1 -1 0 1 -1 0 1 ''' import numpy as np from skimage.io import imread, imshow from skimage.filters import prewitt_h, prewitt_v import matplotlib.pyplot as plt from skimage.transform import resize from skimage.feature import hog image = imread('fireworks.jpeg', as_gray=True) edges_prewitt_hor = prewitt_h(image) imshow(edges_prewitt_hor) plt.show() ''' HOG(Histogram of Oriented Gradients) Feature Descriptor: it is simplified representation of image that contains only most importamt information about image. -It finds shape/structure of object -It finds edge and edge direction Gradient(magnitude) and orientation(direction) -will generate histogram for various regions of image. Histogram is created by taking bins of orientation and putting gradient instead of frequency. And then follwed by normalization. mag = sqrt(x^2 + y^2) or = tan-1(y/x) '''
import HSVConvertDisease import os import numpy as np from skimage.io import imread, imshow from skimage.filters import prewitt_h, prewitt_v import matplotlib.pyplot as plt import cv2 import cv #%matplotlib inline #reading the image #os.system(HSVConvertGreen.py) image = imread(r'test1.jpg', as_gray=True) #image = imread(r'test1.jpg') #hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) #calculating horizontal edges using prewitt kernel edges_prewitt_horizontal = prewitt_h(image) #calculating vertical edges using prewitt kernel5 edges_prewitt_vertical = prewitt_v(image) frame_green = cv2.imread(r'test1.jpg') res1_green = cv2.bitwise_and(frame_green, frame_green, mask=edges_prewitt_vertical) print(edges_prewitt_vertical) #color_img = cv2.cvtColor(edges_prewitt_vertical, cv2.COLOR_GRAY2RGB) cv2.imshow('image.jpg', edges_prewitt_vertical) cv2.imshow('image1.jpg', res1_green)
def horizontal_prewitt_filtering(self, image_object): return scipy.misc.toimage(filters.prewitt_h(image_object))
def horizontal_edge_prewitt(self, image): return prewitt_h(image)
def angle(dx, dy): """Calculate the angles between horizontal and vertical operators.""" return np.mod(np.arctan2(dy, dx), np.pi) true_angle = angle(image_x, image_y) angle_farid = angle(filters.farid_h(image_rotinv), filters.farid_v(image_rotinv)) angle_sobel = angle(filters.sobel_h(image_rotinv), filters.sobel_v(image_rotinv)) angle_scharr = angle(filters.scharr_h(image_rotinv), filters.scharr_v(image_rotinv)) angle_prewitt = angle(filters.prewitt_h(image_rotinv), filters.prewitt_v(image_rotinv)) def diff_angle(angle_1, angle_2): """Calculate the differences between two angles.""" return np.minimum(np.pi - np.abs(angle_1 - angle_2), np.abs(angle_1 - angle_2)) diff_farid = diff_angle(true_angle, angle_farid) diff_sobel = diff_angle(true_angle, angle_sobel) diff_scharr = diff_angle(true_angle, angle_scharr) diff_prewitt = diff_angle(true_angle, angle_prewitt) fig, axes = plt.subplots(nrows=3,
def test_prewitt_h_mask(): """Horizontal prewitt on a masked array should be zero.""" result = filters.prewitt_h(np.random.uniform(size=(10, 10)), np.zeros((10, 10), dtype=bool)) assert_allclose(result, 0)
def test_hprewitt_zeros(): """Horizontal prewitt on an array of all zeros.""" result = filters.prewitt_h(np.zeros((10, 10)), np.ones((10, 10), bool)) assert_allclose(result, 0)
def test_hprewitt_mask(): """Horizontal prewitt on a masked array should be zero.""" np.random.seed(0) result = filters.prewitt_h(np.random.uniform(size=(10, 10)), np.zeros((10, 10), bool)) assert_allclose(result, 0)
edgesh = filters.sobel_h(img) edgesh = img_as_ubyte(edgesh) # sobel 竖直方向边缘检测 edgesv = filters.sobel_v(img) edgesv = img_as_ubyte(edgesv) # Roberts算子 edges_roberts = filters.roberts(img) edges_roberts = img_as_ubyte(edges_roberts) # prewitt算子 edges_prewitt = filters.prewitt(img) edges_prewitt = img_as_ubyte(edges_prewitt) edges_prewitt_h = filters.prewitt_h(img) # 水平方向边缘检测 edges_prewitt_h = img_as_ubyte(edges_prewitt_h) edges_prewitt_v = filters.prewitt_v(img) # 垂直方向边缘检测 edges_prewitt_v = img_as_ubyte(edges_prewitt_v) # canny算子 edges_canny = feature.canny(img, sigma=1.0) # sigma越小,边缘线条越细小 edges_canny = img_as_ubyte(edges_canny) # 高斯拉普拉斯 img1 = cv2.imread(path_Hei, 0) LoG_edge = LoG(img1, 1, (11, 11)) LoG_edge[LoG_edge > 255] = 255 # LoG_edge[LoG_edge>255] = 0