Python cv2.GaussianBlur() Examples

The following are 30 code examples of cv2.GaussianBlur(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cv2 , or try the search function .
Example #1
Source File: motion.py    From object-detection with MIT License 10 votes vote down vote up
def prediction(self, image):
        image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        image = cv2.GaussianBlur(image, (21, 21), 0)
        if self.avg is None:
            self.avg = image.copy().astype(float)
        cv2.accumulateWeighted(image, self.avg, 0.5)
        frameDelta = cv2.absdiff(image, cv2.convertScaleAbs(self.avg))
        thresh = cv2.threshold(
                frameDelta, DELTA_THRESH, 255,
                cv2.THRESH_BINARY)[1]
        thresh = cv2.dilate(thresh, None, iterations=2)
        cnts = cv2.findContours(
                thresh.copy(), cv2.RETR_EXTERNAL,
                cv2.CHAIN_APPROX_SIMPLE)
        cnts = imutils.grab_contours(cnts)
        self.avg = image.copy().astype(float)
        return cnts 
Example #2
Source File: squares.py    From OpenCV-Python-Tutorial with MIT License 9 votes vote down vote up
def find_squares(img):
    img = cv2.GaussianBlur(img, (5, 5), 0)
    squares = []
    for gray in cv2.split(img):
        for thrs in xrange(0, 255, 26):
            if thrs == 0:
                bin = cv2.Canny(gray, 0, 50, apertureSize=5)
                bin = cv2.dilate(bin, None)
            else:
                retval, bin = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY)
            bin, contours, hierarchy = cv2.findContours(bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
            for cnt in contours:
                cnt_len = cv2.arcLength(cnt, True)
                cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True)
                if len(cnt) == 4 and cv2.contourArea(cnt) > 1000 and cv2.isContourConvex(cnt):
                    cnt = cnt.reshape(-1, 2)
                    max_cos = np.max([angle_cos( cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4] ) for i in xrange(4)])
                    if max_cos < 0.1:
                        squares.append(cnt)
    return squares 
Example #3
Source File: plate_locate.py    From EasyPR-python with Apache License 2.0 8 votes vote down vote up
def sobelOperT(self, img, blursize, morphW, morphH):
        '''
            No different with sobelOper ? 
        '''
        blur = cv2.GaussianBlur(img, (blursize, blursize), 0, 0, cv2.BORDER_DEFAULT)

        if len(blur.shape) == 3:
            gray = cv2.cvtColor(blur, cv2.COLOR_RGB2GRAY)
        else:
            gray = blur

        x = cv2.Sobel(gray, cv2.CV_16S, 1, 0, 3)
        absX = cv2.convertScaleAbs(x)
        grad = cv2.addWeighted(absX, 1, 0, 0, 0)

        _, threshold = cv2.threshold(grad, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)

        element = cv2.getStructuringElement(cv2.MORPH_RECT, (morphW, morphH))
        threshold = cv2.morphologyEx(threshold, cv2.MORPH_CLOSE, element)

        return threshold 
Example #4
Source File: corruptions.py    From robustness with Apache License 2.0 7 votes vote down vote up
def disk(radius, alias_blur=0.1, dtype=np.float32):
    if radius <= 8:
        L = np.arange(-8, 8 + 1)
        ksize = (3, 3)
    else:
        L = np.arange(-radius, radius + 1)
        ksize = (5, 5)
    X, Y = np.meshgrid(L, L)
    aliased_disk = np.array((X ** 2 + Y ** 2) <= radius ** 2, dtype=dtype)
    aliased_disk /= np.sum(aliased_disk)

    # supersample disk to antialias
    return cv2.GaussianBlur(aliased_disk, ksize=ksize, sigmaX=alias_blur)


# Tell Python about the C method 
Example #5
Source File: AffineInvariantFeatures.py    From DoNotSnap with GNU General Public License v3.0 7 votes vote down vote up
def affine_skew(self, tilt, phi, img, mask=None):
        h, w = img.shape[:2]
        if mask is None:
            mask = np.zeros((h, w), np.uint8)
            mask[:] = 255
        A = np.float32([[1, 0, 0], [0, 1, 0]])
        if phi != 0.0:
            phi = np.deg2rad(phi)
            s, c = np.sin(phi), np.cos(phi)
            A = np.float32([[c, -s], [s, c]])
            corners = [[0, 0], [w, 0], [w, h], [0, h]]
            tcorners = np.int32(np.dot(corners, A.T))
            x, y, w, h = cv2.boundingRect(tcorners.reshape(1, -1, 2))
            A = np.hstack([A, [[-x], [-y]]])
            img = cv2.warpAffine(img, A, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
        if tilt != 1.0:
            s = 0.8*np.sqrt(tilt * tilt - 1)
            img = cv2.GaussianBlur(img, (0, 0), sigmaX=s, sigmaY=0.01)
            img = cv2.resize(img, (0, 0), fx=1.0 / tilt, fy=1.0, interpolation=cv2.INTER_NEAREST)
            A[0] /= tilt
        if phi != 0.0 or tilt != 1.0:
            h, w = img.shape[:2]
            mask = cv2.warpAffine(mask, A, (w, h), flags=cv2.INTER_NEAREST)
        Ai = cv2.invertAffineTransform(A)
        return img, mask, Ai 
Example #6
Source File: data_augment.py    From ssds.pytorch with MIT License 7 votes vote down vote up
def _elastic(image, p, alpha=None, sigma=None, random_state=None):
    """Elastic deformation of images as described in [Simard2003]_ (with modifications).
    .. [Simard2003] Simard, Steinkraus and Platt, "Best Practices for
         Convolutional Neural Networks applied to Visual Document Analysis", in
         Proc. of the International Conference on Document Analysis and
         Recognition, 2003.
     Based on https://gist.github.com/erniejunior/601cdf56d2b424757de5
     From: 
     https://www.kaggle.com/bguberfain/elastic-transform-for-data-augmentation
    """
    if random.random() > p:
        return image
    if alpha == None:
        alpha = image.shape[0] * random.uniform(0.5,2)
    if sigma == None:
        sigma = int(image.shape[0] * random.uniform(0.5,1))
    if random_state is None:
        random_state = np.random.RandomState(None)

    shape = image.shape[:2]
    
    dx, dy = [cv2.GaussianBlur((random_state.rand(*shape) * 2 - 1) * alpha, (sigma|1, sigma|1), 0) for _ in range(2)]
    x, y = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]))
    x, y = np.clip(x+dx, 0, shape[1]-1).astype(np.float32), np.clip(y+dy, 0, shape[0]-1).astype(np.float32)
    return cv2.remap(image, x, y, interpolation=cv2.INTER_LINEAR, borderValue= 0, borderMode=cv2.BORDER_REFLECT) 
Example #7
Source File: detector.py    From NudeNet with GNU General Public License v3.0 6 votes vote down vote up
def censor(self, img_path, out_path=None, visualize=True, parts_to_blur=['BELLY', 'BUTTOCKS', 'F_BREAST', 'F_GENITALIA', 'M_GENETALIA', 'M_BREAST']):
        if not out_path and not visualize:
            print('No out_path passed and visualize is set to false. There is no point in running this function then.')

        image = cv2.imread(img_path)
        boxes = Detector.detect(self, img_path)
        boxes = [i['box'] for i in boxes if i['label'] in parts_to_blur]

        for box in boxes:
            part = image[box[1]:box[3], box[0]:box[2]]
            image = cv2.rectangle(image, (box[0], box[1]), (box[2], box[3]), (0, 0, 0), cv2.FILLED)
            # image = cv2.GaussianBlur(part,(23, 23), 30)
            # image[box[1]:box[3], box[0]:box[2]] = part
        
        if visualize:
            cv2.imshow("Blurred image", image)
            cv2.waitKey(0)
        
        if out_path:
            cv2.imwrite(out_path, image) 
Example #8
Source File: rule_based.py    From PythonPilot with Apache License 2.0 6 votes vote down vote up
def __apply_canny(self, src, ksize=7, sigma=1.2, low_th=10, high_th=70):
        """Apply canny edge detection.

        Args:
            src (int): Input image BGR.
                       numpy.ndarray, (720, 1280, 3), 0~255

        Returns:
            dst (int): Output image.
                       numpy.ndarray, (720, 1280), 0~1

        """
        gray = cv2.cvtColor(src, cv2.COLOR_RGB2GRAY)
        blur_gray = cv2.GaussianBlur(gray,(ksize, ksize), sigma)
        dst = cv2.Canny(blur_gray, low_th, high_th) // 255

        return dst 
Example #9
Source File: make_imagenet_c_inception.py    From robustness with Apache License 2.0 6 votes vote down vote up
def disk(radius, alias_blur=0.1, dtype=np.float32):
    if radius <= 8:
        L = np.arange(-8, 8 + 1)
        ksize = (3, 3)
    else:
        L = np.arange(-radius, radius + 1)
        ksize = (5, 5)
    X, Y = np.meshgrid(L, L)
    aliased_disk = np.array((X ** 2 + Y ** 2) <= radius ** 2, dtype=dtype)
    aliased_disk /= np.sum(aliased_disk)

    # supersample disk to antialias
    return cv2.GaussianBlur(aliased_disk, ksize=ksize, sigmaX=alias_blur)


# Tell Python about the C method 
Example #10
Source File: make_tinyimagenet_c.py    From robustness with Apache License 2.0 6 votes vote down vote up
def disk(radius, alias_blur=0.1, dtype=np.float32):
    if radius <= 8:
        L = np.arange(-8, 8 + 1)
        ksize = (3, 3)
    else:
        L = np.arange(-radius, radius + 1)
        ksize = (5, 5)
    X, Y = np.meshgrid(L, L)
    aliased_disk = np.array((X ** 2 + Y ** 2) <= radius ** 2, dtype=dtype)
    aliased_disk /= np.sum(aliased_disk)

    # supersample disk to antialias
    return cv2.GaussianBlur(aliased_disk, ksize=ksize, sigmaX=alias_blur)


# Tell Python about the C method 
Example #11
Source File: morpher.py    From yry with Apache License 2.0 6 votes vote down vote up
def correct_color(img1, img2, landmark):
    blur_amount = 0.4 * np.linalg.norm(
        np.mean(landmark[core.LEFT_EYE_POINTS], axis=0)
        - np.mean(landmark[core.RIGHT_EYE_POINTS], axis=0)
    )
    blur_amount = int(blur_amount)

    if blur_amount % 2 == 0:
        blur_amount += 1

    img1_blur = cv2.GaussianBlur(img1, (blur_amount, blur_amount), 0)
    img2_blur = cv2.GaussianBlur(img2, (blur_amount, blur_amount), 0)

    img2_blur += (128 * (img2_blur <= 1.0)).astype(img2_blur.dtype)

    return img2.astype(np.float64) * img1_blur.astype(np.float64) / img2_blur.astype(np.float64) 
Example #12
Source File: augmentation.py    From face_landmark with Apache License 2.0 6 votes vote down vote up
def produce_heatmaps_with_bbox(image,label,h_out,w_out,num_klass,ksize=9,sigma=0):
    heatmap=np.zeros(shape=[h_out,w_out,num_klass])

    h,w,_=image.shape

    for single_box in label:
        if single_box[4]>=0:
            ####box center (x,y)
            center=[(single_box[0]+single_box[2])/2/w,(single_box[1]+single_box[3])/2/h]   ###0-1

            heatmap[round(center[1]*h_out),round(center[0]*w_out),int(single_box[4]) ]=1.

    heatmap = cv2.GaussianBlur(heatmap, (ksize,ksize), sigma)
    am = np.amax(heatmap)
    if am>0:
        heatmap /= am / 255.
    heatmap=np.expand_dims(heatmap,-1)
    return heatmap 
Example #13
Source File: augmentation.py    From face_landmark with Apache License 2.0 6 votes vote down vote up
def produce_heatmaps_with_keypoint(image,label,h_out,w_out,num_klass,ksize=7,sigma=0):
    heatmap=np.zeros(shape=[h_out,w_out,num_klass])

    h,w,_=image.shape

    for i in range(label.shape[0]):
        single_point=label[i]

        if single_point[0]>0 and single_point[1]>0:

            heatmap[int(single_point[1]*(h_out-1)),int(single_point[0]*(w_out-1)),i ]=1.

    heatmap = cv2.GaussianBlur(heatmap, (ksize,ksize), sigma)
    am = np.amax(heatmap)
    if am>0:
        heatmap /= am / 255.
    return heatmap 
Example #14
Source File: make_cifar_c.py    From robustness with Apache License 2.0 6 votes vote down vote up
def disk(radius, alias_blur=0.1, dtype=np.float32):
    if radius <= 8:
        L = np.arange(-8, 8 + 1)
        ksize = (3, 3)
    else:
        L = np.arange(-radius, radius + 1)
        ksize = (5, 5)
    X, Y = np.meshgrid(L, L)
    aliased_disk = np.array((X ** 2 + Y ** 2) <= radius ** 2, dtype=dtype)
    aliased_disk /= np.sum(aliased_disk)

    # supersample disk to antialias
    return cv2.GaussianBlur(aliased_disk, ksize=ksize, sigmaX=alias_blur)


# Tell Python about the C method 
Example #15
Source File: test_detection.py    From object-detection with MIT License 6 votes vote down vote up
def test_motion():
    image = cv2.imread("./imgs/image.jpeg")
    print(image.shape)

    detector = Detector_Motion()

    image2 = cv2.imread("./imgs/image_box.jpg")
    print(image2.shape)
    assert image.shape == image2.shape
    image2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
    image2 = cv2.GaussianBlur(image2, (21, 21), 0)
    detector.avg = image2.astype(float)

    output = detector.prediction(image)
    df = detector.filter_prediction(output, image)
    image = detector.draw_boxes(image, df)
    print(df)
    assert df.shape[0] == 1

    cv2.imwrite("./imgs/outputcv.jpg", image) 
Example #16
Source File: data_provider.py    From exposure with MIT License 6 votes vote down vote up
def augment(self, img, strength):
    s = self.output_size[0]
    start_x = random.randrange(0, img.shape[0] - s + 1)
    start_y = random.randrange(0, img.shape[1] - s + 1)
    img = img[start_x:start_x + s, start_y:start_y + s]
    ### No resizing and rotating....
    # img = rotate_and_crop(img, (random.random() - 0.5) * strength * 300)
    # img = cv2.resize(img, self.output_size)
    if random.random() < 0.5:
      # left-right flip
      img = img[:, ::-1]
    if len(img.shape) < 3:
      img = img[:, :, None]
    if self.blur:
      angle = random.uniform(-1, 1) * 10
      # img = cv2.GaussianBlur(img, (3, 3), 0)
      img = rotate_and_crop(img, angle)
      img = rotate_and_crop(img, -angle)
      img = cv2.resize(img, dsize=self.output_size)
    return img 
Example #17
Source File: imgproc.py    From dataflow with Apache License 2.0 6 votes vote down vote up
def __init__(self, size_range=(0, 3), sigma_range=(0, 0), symmetric=True, max_size=None):
        """
        Args:
            size_range (tuple[int]): Gaussian window size would be 2 * size +
                1, where size is randomly sampled from this [low, high) range.
            sigma_range (tuple[float]): min,max of the sigma value. 0 means
                opencv's default.
            symmetric (bool): whether to use the same size & sigma for x and y.
            max_size (int): deprecated
        """
        super(GaussianBlur, self).__init__()
        if not isinstance(size_range, (list, tuple)):
            size_range = (0, size_range)
        assert isinstance(sigma_range, (list, tuple)), sigma_range
        if max_size is not None:
            log_deprecated("GaussianBlur(max_size=)", "Use size_range= instead!", "2020-09-01")
            size_range = (0, max_size)
        self._init(locals()) 
Example #18
Source File: make_imagenet_c.py    From robustness with Apache License 2.0 6 votes vote down vote up
def disk(radius, alias_blur=0.1, dtype=np.float32):
    if radius <= 8:
        L = np.arange(-8, 8 + 1)
        ksize = (3, 3)
    else:
        L = np.arange(-radius, radius + 1)
        ksize = (5, 5)
    X, Y = np.meshgrid(L, L)
    aliased_disk = np.array((X ** 2 + Y ** 2) <= radius ** 2, dtype=dtype)
    aliased_disk /= np.sum(aliased_disk)

    # supersample disk to antialias
    return cv2.GaussianBlur(aliased_disk, ksize=ksize, sigmaX=alias_blur)


# Tell Python about the C method 
Example #19
Source File: mosse.py    From OpenCV-Python-Tutorial with MIT License 6 votes vote down vote up
def __init__(self, frame, rect):
        x1, y1, x2, y2 = rect
        w, h = map(cv2.getOptimalDFTSize, [x2-x1, y2-y1])
        x1, y1 = (x1+x2-w)//2, (y1+y2-h)//2
        self.pos = x, y = x1+0.5*(w-1), y1+0.5*(h-1)
        self.size = w, h
        img = cv2.getRectSubPix(frame, (w, h), (x, y))

        self.win = cv2.createHanningWindow((w, h), cv2.CV_32F)
        g = np.zeros((h, w), np.float32)
        g[h//2, w//2] = 1
        g = cv2.GaussianBlur(g, (-1, -1), 2.0)
        g /= g.max()

        self.G = cv2.dft(g, flags=cv2.DFT_COMPLEX_OUTPUT)
        self.H1 = np.zeros_like(self.G)
        self.H2 = np.zeros_like(self.G)
        for i in xrange(128):
            a = self.preprocess(rnd_warp(img))
            A = cv2.dft(a, flags=cv2.DFT_COMPLEX_OUTPUT)
            self.H1 += cv2.mulSpectrums(self.G, A, 0, conjB=True)
            self.H2 += cv2.mulSpectrums(     A, A, 0, conjB=True)
        self.update_kernel()
        self.update(frame) 
Example #20
Source File: SudokuExtractor.py    From SolveSudoku with MIT License 6 votes vote down vote up
def pre_process_image(img, skip_dilate=False):
	"""Uses a blurring function, adaptive thresholding and dilation to expose the main features of an image."""

	# Gaussian blur with a kernal size (height, width) of 9.
	# Note that kernal sizes must be positive and odd and the kernel must be square.
	proc = cv2.GaussianBlur(img.copy(), (9, 9), 0)

	# Adaptive threshold using 11 nearest neighbour pixels
	proc = cv2.adaptiveThreshold(proc, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)

	# Invert colours, so gridlines have non-zero pixel values.
	# Necessary to dilate the image, otherwise will look like erosion instead.
	proc = cv2.bitwise_not(proc, proc)

	if not skip_dilate:
		# Dilate the image to increase the size of the grid lines.
		kernel = np.array([[0., 1., 0.], [1., 1., 1.], [0., 1., 0.]],np.uint8)
		proc = cv2.dilate(proc, kernel)

	return proc 
Example #21
Source File: imgproc.py    From DDRL with Apache License 2.0 5 votes vote down vote up
def __init__(self, max_size=3):
        """:params max_size: (maximum kernel size-1)/2"""
        super(GaussianBlur, self).__init__()
        self._init(locals()) 
Example #22
Source File: line_graph.py    From PPGNet with MIT License 5 votes vote down vote up
def line_map(self, size, scale_x=1., scale_y=1., line_width=2.):
        if isinstance(size, tuple):
            lmap = np.zeros(size, dtype=np.uint8)
        else:
            lmap = np.zeros((size, size), dtype=np.uint8)
        for line_seg in self._line_segs:
            for ind_junc1, ind_junc2 in combinations(line_seg["junctions"], 2):
                x1, y1 = self._junctions[ind_junc1]
                x2, y2 = self._junctions[ind_junc2]
                x1, x2 = int(x1 * scale_x + 0.5), int(x2 * scale_x + 0.5)
                y1, y2 = int(y1 * scale_y + 0.5), int(y2 * scale_y + 0.5)
                lmap = cv2.line(lmap, (x1, y1), (x2, y2), 255, int(line_width), cv2.LINE_AA)
        # lmap = cv2.GaussianBlur(lmap, (int(line_width), int(line_width)), 1)
        # lmap[lmap > 1] = 1
        return lmap 
Example #23
Source File: part-6-lane-finder.py    From pygta5 with GNU General Public License v3.0 5 votes vote down vote up
def process_img(image):
    original_image = image
    # convert to gray
    processed_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # edge detection
    processed_img =  cv2.Canny(processed_img, threshold1 = 200, threshold2=300)
    
    processed_img = cv2.GaussianBlur(processed_img,(5,5),0)
    
    vertices = np.array([[10,500],[10,300],[300,200],[500,200],[800,300],[800,500],
                         ], np.int32)

    processed_img = roi(processed_img, [vertices])

    # more info: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html
    #                                     rho   theta   thresh  min length, max gap:        
    lines = cv2.HoughLinesP(processed_img, 1, np.pi/180, 180,      20,       15)
    try:
        l1, l2 = draw_lanes(original_image,lines)
        cv2.line(original_image, (l1[0], l1[1]), (l1[2], l1[3]), [0,255,0], 30)
        cv2.line(original_image, (l2[0], l2[1]), (l2[2], l2[3]), [0,255,0], 30)
    except Exception as e:
        print(str(e))
        pass
    try:
        for coords in lines:
            coords = coords[0]
            try:
                cv2.line(processed_img, (coords[0], coords[1]), (coords[2], coords[3]), [255,0,0], 3)
                
                
            except Exception as e:
                print(str(e))
    except Exception as e:
        pass

    return processed_img,original_image 
Example #24
Source File: Preprocess.py    From ALPR-Indonesia with MIT License 5 votes vote down vote up
def preprocess(imgOriginal):
    #coba = cv2.cvtColor(imgOriginal, cv2.COLOR_BGR2HSV)
    #cv2.imshow("hsv", coba )
    imgGrayscale = extractValue(imgOriginal)
    #cv2.imshow("imgGrayscale", imgGrayscale )

    imgGrayscale = np.invert(imgGrayscale) # last best use this
    #cv2.imshow("invert", imgGrayscale )
    imgMaxContrastGrayscale = maximizeContrast(imgGrayscale)
    #cv2.imshow("imgMaxContrastGrayscale", imgMaxContrastGrayscale )
    #imgMaxContrastGrayscale = np.invert(imgMaxContrastGrayscale)
    height, width = imgGrayscale.shape

    imgBlurred = np.zeros((height, width, 1), np.uint8)
    #cv2.imshow("c_3", imgBlurred )

    imgBlurred = cv2.GaussianBlur(imgMaxContrastGrayscale, GAUSSIAN_SMOOTH_FILTER_SIZE, 0)
    #cv2.imshow("imgBlurred", imgBlurred )
    #imgBlurred = np.invert(imgBlurred)
    imgThresh = cv2.adaptiveThreshold(imgBlurred, THRESHOLD_VALUE , cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, ADAPTIVE_THRESH_BLOCK_SIZE, ADAPTIVE_THRESH_WEIGHT)
    #imgThresh = np.invert(imgThresh)
    #cv2.imshow("cobaaa", imgThresh)

    return imgGrayscale, imgThresh
# end function

################################################################################################### 
Example #25
Source File: invert_imageData.py    From ALPR-Indonesia with MIT License 5 votes vote down vote up
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("-d", "--image_train",
            help = "path for the images that you're going to invert")
    args = vars(ap.parse_args())
    if args.get("image", True):
        imgTrainingNumbers = cv2.imread(args["image_train"]) # read in training numbers image
        if imgTrainingNumbers is None:
            print "error: image not read from file \n\n"        # print error message to std out
            os.system("pause")                                  # pause so user can see error message
            return
    else:
        print("Please add -d or --image_train argument")

    imgGray = cv2.cvtColor(imgTrainingNumbers, cv2.COLOR_BGR2GRAY)          # get grayscale image
    imgBlurred = cv2.GaussianBlur(imgGray, (5,5), 0)                        # blur

                                                        # filter image from grayscale to black and white
    imgThresh = cv2.adaptiveThreshold(imgBlurred,                           # input image
                                      0,                                  # make pixels that pass the threshold full white
                                      cv2.ADAPTIVE_THRESH_GAUSSIAN_C,       # use gaussian rather than mean, seems to give better results
                                      cv2.THRESH_BINARY_INV,                # invert so foreground will be white, background will be black
                                      11,                                   # size of a pixel neighborhood used to calculate threshold value
                                      2)                                    # constant subtracted from the mean or weighted mean

    imgTrainingNumbers = np.invert(imgTrainingNumbers)
    cv2.imwrite("invert_"+args["image_train"],imgTrainingNumbers)
    cv2.imwrite("imgThresh_"+args["image_train"],imgThresh)
    return

################################################################################################### 
Example #26
Source File: data_utils.py    From conditional-motion-propagation with MIT License 5 votes vote down vote up
def get_edge(data, blur=False):
    if blur:
        data = cv2.GaussianBlur(data, (3, 3), 1.)
    sobel = np.array([[1,0,-1],[2,0,-2],[1,0,-1]]).astype(np.float32)
    ch_edges = []
    for k in range(data.shape[2]):
        edgex = signal.convolve2d(data[:,:,k], sobel, boundary='symm', mode='same')
        edgey = signal.convolve2d(data[:,:,k], sobel.T, boundary='symm', mode='same')
        ch_edges.append(np.sqrt(edgex**2 + edgey**2))
    return sum(ch_edges) 
Example #27
Source File: mnist_helpers.py    From mnist-helper with MIT License 5 votes vote down vote up
def prepare_test_image(image, width ,resize_shape, negated=False):
    """
    This function normalizes an an already padded image and flattens it into a
    row vector
    :param image: the input image
    :type image: numpy nd array

    :param resize_shape: a tuple denoting the shape of the padded image
    :type resize_shape: tuple

    :param negated: a flag to know if the input image is a negated one
    :type negated: boolean

    :returns : a 1-D array
    """

    # negate the image 
    if not negated:
        image = 255-image
    
    # resizing the image 
    resized_image = resize_img(image, resize_shape, negated=True)
    #resized_image = width_normalization(image, width, resize_shape, negated=True)
    
    # gaussian filtering
    resized_image = cv2.GaussianBlur(resized_image,(3,3), 0)
    # deskew
    #deskewed_image = deskew(resized_image, resize_shape)
    
    # normalize the image values to fit in the range [0,1]
    norm_image = numpy.asarray(resized_image, dtype=numpy.float32) / 255.

    # Flatten the image to a 1-D vector and return
    return norm_image.reshape(1, resize_shape[0] * resize_shape[1]) 
Example #28
Source File: transforms.py    From VS-ReID with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def blur(img, kenrel_size=(5, 5), sigma=(1e-6, 0.6)):
    img = cv2.GaussianBlur(img, kenrel_size, random.uniform(*sigma))
    return img 
Example #29
Source File: imutils.py    From pytorch-cpn with GNU General Public License v3.0 5 votes vote down vote up
def generate_heatmap(heatmap, pt, sigma):
    heatmap[int(pt[1])][int(pt[0])] = 1
    heatmap = cv2.GaussianBlur(heatmap, sigma, 0)
    am = np.amax(heatmap)
    heatmap /= am / 255
    return heatmap


# =============================================================================
# Helpful display functions
# ============================================================================= 
Example #30
Source File: dataset_utils.py    From rpg_davis_simulator with GNU General Public License v3.0 5 votes vote down vote up
def preprocess_image(img, use_log=True, blur_size=0):
        if blur_size > 0:
            img = cv2.GaussianBlur(img, (blur_size,blur_size), 0)
            
        if use_log:
            img = safe_log(img)
        return img