Python cv2.medianBlur() Examples

The following are 30 code examples of cv2.medianBlur(). 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: camera_test.py    From crop_row_detection with GNU General Public License v3.0 7 votes vote down vote up
def main():
	capture = cv2.VideoCapture(0)
	_, image = capture.read()
	previous = image.copy()
	
	
	while (cv2.waitKey(1) < 0):
		_, image = capture.read()
		diff = cv2.absdiff(image, previous)
		#image = cv2.flip(image, 3)
		#image = cv2.norm(image)
		_, diff = cv2.threshold(diff, 32, 0, cv2.THRESH_TOZERO)
		_, diff = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY)
		
		diff = cv2.medianBlur(diff, 5)
		
		cv2.imshow('video', diff)
		previous = image.copy()
		
	capture.release()
	cv2.destroyAllWindows() 
Example #2
Source File: getPaper.py    From signature_extractor with MIT License 6 votes vote down vote up
def getPaperFromImage(img):
    gImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    bImg = cv2.medianBlur(src = gImg, ksize = 51)

    threshold, _ = cv2.threshold(src = bImg, thresh = 0, maxval = 255, type = cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    cannyImg = cv2.Canny(image = bImg, threshold1 = 0.5 * threshold, threshold2 = threshold)

    _, contours, _ = cv2.findContours(image = cannyImg.copy(), mode = cv2.RETR_TREE, method = cv2.CHAIN_APPROX_SIMPLE)

    maxRect = Rect(0, 0, 0, 0)
    for contour in contours:
        x, y, w, h = cv2.boundingRect(points = contour)
        currentArea = w * h
        if currentArea > maxRect.getArea():
            maxRect.set(x, y, w, h)

    return img[maxRect.y : maxRect.y + maxRect.h, maxRect.x : maxRect.x + maxRect.w] 
Example #3
Source File: cvmgr.py    From sia-cog with MIT License 6 votes vote down vote up
def extracttext(imgpath, preprocess):
    if imgpath.startswith('http://') or imgpath.startswith('https://') or imgpath.startswith('ftp://'):
        image = url_to_image(imgpath)
    else:
        image = cv2.imread(imgpath)

    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    if preprocess == "thresh":
        gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
    elif preprocess == "blur":
        gray = cv2.medianBlur(gray, 3)

    filename = "{}.png".format(os.getpid())
    cv2.imwrite(filename, gray)
    text = pytesseract.image_to_string(Image.open(filename))

    os.remove(filename)
    return {"text": text} 
Example #4
Source File: raidnearby.py    From PGSS with GNU General Public License v3.0 6 votes vote down vote up
def getMonMask(self, img):
        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

        # define range of blue color in HSV
        lower_blue = np.array([94, 130, 70])
        upper_blue = np.array([114, 160, 110])

        # Threshold the HSV image to get only shadow colors
        mask = cv2.inRange(hsv, lower_blue, upper_blue)
        kernel = np.ones((2, 2), np.uint8)
        mask = cv2.dilate(mask, kernel, iterations=1)
        final_mask = 255 - cv2.medianBlur(mask, 3) # invert mask

        return final_mask

    # Detect gym from raid sighting image 
Example #5
Source File: preprocessing.py    From minian with GNU General Public License v3.0 6 votes vote down vote up
def denoise(varr, method, **kwargs):
    if method == 'gaussian':
        func = cv2.GaussianBlur
    elif method == 'anisotropic':
        func = anisotropic_diffusion
    elif method == 'median':
        func = cv2.medianBlur
    elif method == 'bilateral':
        func = cv2.bilateralFilter
    else:
        raise NotImplementedError(
            "denoise method {} not understood".format(method))
    res = xr.apply_ufunc(
        func,
        varr,
        input_core_dims=[['height', 'width']],
        output_core_dims=[['height', 'width']],
        vectorize=True,
        dask='parallelized',
        output_dtypes=[varr.dtype],
        kwargs=kwargs)
    return res.rename(varr.name + "_denoised") 
Example #6
Source File: imgaug.py    From imgaug with MIT License 6 votes vote down vote up
def _median_pool_cv2(arr, block_size, pad_mode, pad_cval):
    from imgaug.augmenters.size import pad_to_multiples_of

    ndim_in = arr.ndim

    shape = arr.shape
    if shape[0] % block_size != 0 or shape[1] % block_size != 0:
        arr = pad_to_multiples_of(
            arr,
            height_multiple=block_size,
            width_multiple=block_size,
            mode=pad_mode,
            cval=pad_cval
        )

    arr = cv2.medianBlur(arr, block_size)

    if arr.ndim < ndim_in:
        arr = arr[:, :, np.newaxis]

    start_height = (block_size - 1) // 2
    start_width = (block_size - 1) // 2
    return arr[start_height::block_size, start_width::block_size] 
Example #7
Source File: idcardocr.py    From idcardocr with GNU General Public License v3.0 6 votes vote down vote up
def get_name(img):
        #    cv2.imshow("method3", img)
        #    cv2.waitKey()
        print('name')
        _, _, red = cv2.split(img) #split 会自动将UMat转换回Mat
        red = cv2.UMat(red)
        red = hist_equal(red)
        red = cv2.adaptiveThreshold(red, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 151, 50)
        #    red = cv2.medianBlur(red, 3)
        red = img_resize(red, 150)
        img = img_resize(img, 150)
        # showimg(red)
        # cv2.imwrite('name.png', red)
        #    img2 = Image.open('address.png')
        # img = Image.fromarray(cv2.UMat.get(red).astype('uint8'))
        #return get_result_vary_length(red, 'chi_sim', img, '-psm 7')
        return get_result_vary_length(red, 'chi_sim', img, '--psm 7')
        # return punc_filter(pytesseract.image_to_string(img, lang='chi_sim', config='-psm 13').replace(" ","")) 
Example #8
Source File: getBlobTrajectories.py    From tierpsy-tracker with MIT License 6 votes vote down vote up
def _get_blob_mask(ROI_image, thresh, thresh_block_size, is_light_background, analysis_type):
    # get binary image, 
    if is_light_background:
        ## apply a median filter to reduce rough edges / sharpen the boundary btw worm and background
        ROI_image_th = cv2.medianBlur(ROI_image, 3)
        ROI_mask = ROI_image_th < thresh
    else:
        if analysis_type == "PHARYNX":
            # for fluorescent pharynx labeled images, refine the threshold with a local otsu (http://scikit-image.org/docs/dev/auto_examples/plot_local_otsu.html)
            # this compensates for local variations in brightness in high density regions, when many worms are close to each other
            ROI_rank_otsu = skf.rank.otsu(ROI_image, skm.disk(thresh_block_size))
            ROI_mask = (ROI_image>ROI_rank_otsu)
            # as a local threshold introcudes artifacts at the edge of the mask, also use a global threshold to cut these out
            ROI_mask &= (ROI_image>=thresh)
        else:
            # this case applies for example to worms where the whole body is fluorecently labeled
            ROI_image_th = cv2.medianBlur(ROI_image, 3)
            ROI_mask = ROI_image_th >= thresh
        
    ROI_mask &= (ROI_image != 0)
    ROI_mask = ROI_mask.astype(np.uint8)

    return ROI_mask, thresh # returning thresh here seems redundant, as it isn't actually changed 
Example #9
Source File: getFoodContourMorph.py    From tierpsy-tracker with MIT License 6 votes vote down vote up
def get_dark_mask(full_data):
    #get darker objects that are unlikely to be worm
    if full_data.shape[0] < 2:
        #nothing to do here returning
        return np.zeros((full_data.shape[1], full_data.shape[2]), np.uint8)
    
    #this mask shoulnd't contain many worms
    img_h = cv2.medianBlur(np.max(full_data, axis=0), 5)
    #this mask is likely to contain a lot of worms
    img_l = cv2.medianBlur(np.min(full_data, axis=0), 5)
    
    #this is the difference (the tagged pixels should be mostly worms)
    img_del = img_h-img_l
    th_d = threshold_otsu(img_del)
    
    #this is the maximum of the minimum pixels of the worms...
    th = np.max(img_l[img_del>th_d])
    #this is what a darkish mask should look like
    dark_mask = cv2.dilate((img_h<th).astype(np.uint8), disk(11))
    
    return dark_mask 
Example #10
Source File: getBlobTrajectories.py    From tierpsy-tracker with MIT License 6 votes vote down vote up
def getBlobsSimple(in_data, blob_params):
    frame_number, image = in_data
    min_area, worm_bw_thresh_factor, strel_size = blob_params
    
    
    img_m = cv2.medianBlur(image, 3)
    
    valid_pix = img_m[img_m>0]
    if len(valid_pix) == 0:
        return []
    
    th = _thresh_bw(valid_pix)*worm_bw_thresh_factor
    
    _, bw = cv2.threshold(img_m, th,255,cv2.THRESH_BINARY)
    if np.all(strel_size):
        strel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, strel_size)
        bw = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, strel)

    cnts, hierarchy = cv2.findContours(bw, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2:]
    
    
    blobs_data = _cnt_to_props(cnts, frame_number, th, min_area)
    return blobs_data 
Example #11
Source File: Cartoonlization.py    From rabbitVE with GNU General Public License v3.0 6 votes vote down vote up
def cartoonise(self, img_rgb, num_down, num_bilateral, medianBlur, D, sigmaColor, sigmaSpace):
        # 用高斯金字塔降低取样
        img_color = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR)
        for _ in range(num_down):
            img_color = cv2.pyrDown(img_color)
        # 重复使用小的双边滤波代替一个大的滤波
        for _ in range(num_bilateral):
            img_color = cv2.bilateralFilter(img_color, d=D, sigmaColor=sigmaColor, sigmaSpace=sigmaSpace)
        # 升采样图片到原始大小
        for _ in range(num_down):
            img_color = cv2.pyrUp(img_color)
        if not self.Save_Edge:
            img_cartoon = img_color
        else:
            img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
            img_blur = cv2.medianBlur(img_gray, medianBlur)
            img_edge = cv2.adaptiveThreshold(img_blur, 255,
                                             cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                             cv2.THRESH_BINARY,
                                             blockSize=self.Adaptive_Threshold_Block_Size,
                                             C=self.C)
            img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB)
            img_edge = cv2.resize(img_edge, img_color.shape[:2][::-1])
            img_cartoon = cv2.bitwise_and(img_color, img_edge)
        return cv2.cvtColor(img_cartoon, cv2.COLOR_RGB2BGR) 
Example #12
Source File: thresholding.py    From smashscan with MIT License 6 votes vote down vote up
def param_filter(self, frame):
        # Apply pre-blur according to trackbar value.
        if self.pre_blur_val == 1:
            frame = cv2.GaussianBlur(frame, (5, 5), 0)
        elif self.pre_blur_val == 2:
            frame = cv2.medianBlur(frame, 5)

        # Apply a thresholding method according to trackbar value.
        if self.thresh_flag:
            _, frame = cv2.threshold(frame, 127, 255, cv2.THRESH_BINARY)
        else:
            _, frame = cv2.threshold(frame, 127, 255, cv2.THRESH_OTSU)

        # Apply post-blur according to trackbar value.
        if self.post_blur_val:
            frame = cv2.medianBlur(frame, 5)

        return frame


    # Apply filterrs to frame according to contour parameters. 
Example #13
Source File: gui.py    From DeepWarp with Apache License 2.0 6 votes vote down vote up
def generate(path):
    global cur_rgb_image
    if cur_rgb_image is not None:
        print('process......')
        el_img, er_img, angle, re_angle, os_l, os_r = get_input_from_image()
        el, er = get_output_from_sess(el_img, er_img, angle, re_angle)

        new_image = np.copy(cur_rgb_image)
        new_image = helper.replace(new_image, el, os_l)
        rgb_new_image = helper.replace(new_image, er, os_r)
        # bgr_new_image = cv2.cvtColor(rgb_new_image, cv2.COLOR_RGB2BGR)
        # cv2.imshow('deepwarp', bgr_new_image)

        # if chk_btn.get() == True:
        #     rgb_new_image = cv2.medianBlur(rgb_new_image, 3)

        global label_img
        img_wapper = ImageTk.PhotoImage(Image.fromarray(rgb_new_image))
        label_img.configure(image=img_wapper)
        label_img.image = img_wapper
        return rgb_new_image
    else:
        print('no image......')
        return None 
Example #14
Source File: cartoonizing.py    From Mastering-OpenCV-4-with-Python with MIT License 6 votes vote down vote up
def sketch_image(img):
    """Sketches the image applying a laplacian operator to detect the edges"""

    # Convert to gray scale
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Apply median filter
    img_gray = cv2.medianBlur(img_gray, 5)

    # Detect edges using cv2.Laplacian()
    edges = cv2.Laplacian(img_gray, cv2.CV_8U, ksize=5)

    # Threshold the edges image:
    ret, thresholded = cv2.threshold(edges, 70, 255, cv2.THRESH_BINARY_INV)

    return thresholded 
Example #15
Source File: 05_cartoonizing.py    From OpenCV-3-x-with-Python-By-Example with MIT License 6 votes vote down vote up
def cartoonize_image(img, ksize=5, sketch_mode=False):
    num_repetitions, sigma_color, sigma_space, ds_factor = 10, 5, 7, 4 
    # Convert image to grayscale 
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
 
    # Apply median filter to the grayscale image 
    img_gray = cv2.medianBlur(img_gray, 7) 
 
    # Detect edges in the image and threshold it 
    edges = cv2.Laplacian(img_gray, cv2.CV_8U, ksize=ksize) 
    ret, mask = cv2.threshold(edges, 100, 255, cv2.THRESH_BINARY_INV) 
 
    # 'mask' is the sketch of the image 
    if sketch_mode: 
        return cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR) 
 
    # Resize the image to a smaller size for faster computation 
    img_small = cv2.resize(img, None, fx=1.0/ds_factor, fy=1.0/ds_factor, interpolation=cv2.INTER_AREA)
 
    # Apply bilateral filter the image multiple times 
    for i in range(num_repetitions): 
        img_small = cv2.bilateralFilter(img_small, ksize, sigma_color, sigma_space) 
 
    img_output = cv2.resize(img_small, None, fx=ds_factor, fy=ds_factor, interpolation=cv2.INTER_LINEAR) 
 
    dst = np.zeros(img_gray.shape) 
 
    # Add the thick boundary lines to the image using 'AND' operator 
    dst = cv2.bitwise_and(img_output, img_output, mask=mask) 
    return dst 
Example #16
Source File: functional.py    From dsb2018_topcoders with MIT License 5 votes vote down vote up
def median_blur(img, ksize):
    return cv2.medianBlur(img, ksize) 
Example #17
Source File: detection.py    From BlurDetection2 with MIT License 5 votes vote down vote up
def pretty_blur_map(blur_map: numpy.array, sigma: int = 5, min_abs: float = 0.5):
    abs_image = numpy.abs(blur_map).astype(numpy.float32)
    abs_image[abs_image < min_abs] = min_abs

    abs_image = numpy.log(abs_image)
    cv2.blur(abs_image, (sigma, sigma))
    return cv2.medianBlur(abs_image, sigma) 
Example #18
Source File: blursharpen.py    From DeepFaceLab with GNU General Public License v3.0 5 votes vote down vote up
def blursharpen (img, sharpen_mode=0, kernel_size=3, amount=100):
    if kernel_size % 2 == 0:
        kernel_size += 1
    if amount > 0:
        if sharpen_mode == 1: #box
            kernel = np.zeros( (kernel_size, kernel_size), dtype=np.float32)
            kernel[ kernel_size//2, kernel_size//2] = 1.0
            box_filter = np.ones( (kernel_size, kernel_size), dtype=np.float32) / (kernel_size**2)
            kernel = kernel + (kernel - box_filter) * amount
            return cv2.filter2D(img, -1, kernel)
        elif sharpen_mode == 2: #gaussian
            blur = cv2.GaussianBlur(img, (kernel_size, kernel_size) , 0)
            img = cv2.addWeighted(img, 1.0 + (0.5 * amount), blur, -(0.5 * amount), 0)
            return img
    elif amount < 0:
        n = -amount
        while n > 0:

            img_blur = cv2.medianBlur(img, 5)
            if int(n / 10) != 0:
                img = img_blur
            else:
                pass_power = (n % 10) / 10.0
                img = img*(1.0-pass_power)+img_blur*pass_power
            n = max(n-10,0)

        return img
    return img 
Example #19
Source File: augmentor.py    From A-Light-and-Fast-Face-Detector-for-Edge-Devices with MIT License 5 votes vote down vote up
def blur(image, mode='random', kernel_size=3, sigma=1):
        """

        :param image:
        :param mode: options 'normalized' 'gaussian' 'median'
        :param kernel_size:
        :param sigma: used for gaussian blur
        :return:
        """
        if image.dtype != numpy.uint8:
            print('Input image is not uint8!')
            return None

        if mode == 'random':
            mode = random.choice(['normalized', 'gaussian', 'median'])

        if mode == 'normalized':
            result = cv2.blur(image, (kernel_size, kernel_size))
        elif mode == 'gaussian':
            result = cv2.GaussianBlur(image, (kernel_size, kernel_size), sigmaX=sigma, sigmaY=sigma)
        elif mode == 'median':
            result = cv2.medianBlur(image, kernel_size)
        else:
            print('Blur mode is not supported: %s.' % mode)
            result = image
        return result 
Example #20
Source File: video.py    From cv with MIT License 5 votes vote down vote up
def cartoonize_image(img, ds_factor=4, sketch_mode=False):
    #convert to gray scale
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    #apply median filter
    img_gray = cv2.medianBlur(img_gray, 7)

    #detect edges and threshold the imag
    edges = cv2.Laplacian(img_gray, cv2.CV_8U, ksize=5)
    ret, mask = cv2.threshold(edges, 100, 255, cv2.THRESH_BINARY_INV)
    
    #mask is the sketch of the image
    if sketch_mode:
        return cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
    
    img_small = cv2.resize(img, None, fx=1.0/ds_factor, fy=1.0/ds_factor, interpolation = cv2.INTER_AREA)
    num_repetitions = 10
    sigma_color = 5
    sigma_space = 7
    size = 5
    
    #apply bilateral filter multiple times
    for i in range(num_repetitions):
        img_small = cv2.bilateralFilter(img_small, size, sigma_color, sigma_space)
    
    img_output = cv2.resize(img_small, None, fx=ds_factor, fy=ds_factor, interpolation=cv2.INTER_LINEAR)
    dst = np.zeros(img_gray.shape)
    
    dst = cv2.bitwise_and(img_output, img_output, mask=mask)
    return dst 
Example #21
Source File: 03_median_filtering.py    From Practical-Computer-Vision with MIT License 5 votes vote down vote up
def main():
    # read an image 
    img = cv2.imread('../figures/flower.png')

    
    median1 = cv2.medianBlur(img,3)
    median2 = cv2.medianBlur(img,5)
    median3 = cv2.medianBlur(img,7)
    
    
    # Do plot
    plot_cv_img(img, median1, median2, median3) 
Example #22
Source File: image_transformation.py    From Sign-Language-Recognition with MIT License 5 votes vote down vote up
def make_background_black(frame):
    """
    Makes everything apart from the main object of interest to be
    black in color.
    """
    logger.debug("Making background black...")

    # Convert from RGB to HSV
    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # Prepare the first mask.
    # Tuned parameters to match the skin color of the input images...
    lower_boundary = np.array([0, 40, 30], dtype="uint8")
    upper_boundary = np.array([43, 255, 254], dtype="uint8")
    skin_mask = cv2.inRange(frame, lower_boundary, upper_boundary)

    # Apply a series of erosions and dilations to the mask using an
    # elliptical kernel
    kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
    skin_mask = cv2.erode(skin_mask, kernel, iterations=2)
    skin_mask = cv2.dilate(skin_mask, kernel, iterations=2)

    # Prepare the second mask
    lower_boundary = np.array([170, 80, 30], dtype="uint8")
    upper_boundary = np.array([180, 255, 250], dtype="uint8")
    skin_mask2 = cv2.inRange(frame, lower_boundary, upper_boundary)

    # Combine the effect of both the masks to create the final frame.
    skin_mask = cv2.addWeighted(skin_mask, 0.5, skin_mask2, 0.5, 0.0)
    # Blur the mask to help remove noise.
    # skin_mask = cv2.medianBlur(skin_mask, 5)
    frame_skin = cv2.bitwise_and(frame, frame, mask=skin_mask)
    frame = cv2.addWeighted(frame, 1.5, frame_skin, -0.5, 0)
    frame_skin = cv2.bitwise_and(frame, frame, mask=skin_mask)

    logger.debug("Done!")
    return frame_skin 
Example #23
Source File: functional.py    From dsb2018_topcoders with MIT License 5 votes vote down vote up
def median_blur(img, ksize):
    return cv2.medianBlur(img, ksize) 
Example #24
Source File: functional.py    From dsb2018_topcoders with MIT License 5 votes vote down vote up
def median_blur(img, ksize):
    return cv2.medianBlur(img, ksize) 
Example #25
Source File: SaltPepperNoise.py    From Finger-Detection-and-Tracking with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def main():
    probability = 0.05  # only 5% of the total image will have noise
    imagepath = "../data/4.1.08.tiff"
    imagebgr = cv2.imread(imagepath, 1)
    imagergb = cv2.cvtColor(imagebgr, cv2.COLOR_BGR2RGB)

    rows, columns, channels = imagergb.shape

    for i in range(rows):
        for j in range(columns):
            rand = random.random()
            if rand < (probability / 2):
                # pepper noise
                imagergb[i][j] = [0, 0, 0]
            elif rand < probability:
                # salt noise
                imagergb[i][j] = [255, 255, 255]

    # Median filter to remove noise from image
    median_filter = cv2.medianBlur(imagebgr, 5)
    median_filter = cv2.cvtColor(median_filter, cv2.COLOR_BGR2RGB)

    plt.subplot(1, 2, 1)
    plt.imshow(imagergb)
    plt.title("Salt and Pepper Noise Image")

    plt.subplot(1, 2, 2)
    plt.imshow(median_filter)
    plt.title("Median Filter De-Noising (Salt and Pepper)")

    plt.show() 
Example #26
Source File: SuironCV.py    From suiron with MIT License 5 votes vote down vote up
def get_median_blur(gray_frame):
    return cv2.medianBlur(gray_frame, 5)

# Canny edge detection 
Example #27
Source File: pretreatment.py    From captcha_trainer with Apache License 2.0 5 votes vote down vote up
def median_blur(self, value, modify=False) -> np.ndarray:
        if not value:
            return self.origin
        value = random.randint(0, value)
        value = value + 1 if value % 2 == 0 else value
        _smooth = cv2.medianBlur(self.origin, value)
        if modify:
            self.origin = _smooth
        return _smooth 
Example #28
Source File: EyeCanSee.py    From cv-lane with Apache License 2.0 5 votes vote down vote up
def filter_smooth_thres(self, RANGE, color):
        for (lower, upper) in RANGE:
            lower = np.array(lower, dtype='uint8')
            upper = np.array(upper, dtype='uint8')

            mask_bottom = cv2.inRange(self.img_roi_bottom_hsv, lower, upper)
            mask_top = cv2.inRange(self.img_roi_top_hsv, lower, upper)

        blurred_bottom = cv2.medianBlur(mask_bottom, 5)
        blurred_top = cv2.medianBlur(mask_top, 5)

        # Morphological transformation
        kernel = np.ones((2, 2), np.uint8)
        smoothen_bottom = blurred_bottom #cv2.morphologyEx(blurred, cv2.MORPH_OPEN, kernel, iterations=5)
        smoothen_top = blurred_top  # cv2.morphologyEx(blurred, cv2.MORPH_OPEN, kernel, iterations=5)

        """
        if self.debug:
            cv2.imshow('mask bottom ' + color, mask_bottom)
            cv2.imshow('blurred bottom' + color, blurred_bottom)

            cv2.imshow('mask top ' + color, mask_top)
            cv2.imshow('blurred top' + color, blurred_top)
        """

        return smoothen_bottom, smoothen_top

    # Gets metadata from our contours 
Example #29
Source File: text_recognition.py    From MemePolice_bot with GNU General Public License v2.0 5 votes vote down vote up
def text_recognition(post):
    meme_name = "temp"  # We would just call all the temporary images as "temp"
    request.urlretrieve(post.url, filename=meme_name)  # Here we are downloading the appropriate image (png, jpg, jpeg, bmp)
    image = cv2.imread(meme_name)  # We load up the image using opencv
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  # Turning the image to grayscale
    gray = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]  # Making a threshold for the image, text will be more apparent
    gray = cv2.medianBlur(gray, 3)  # Adding some blur, useful for really noisy images
    filename = "{}-ocr.png".format(meme_name)  # Making the temporary, ready file for text recognition
    cv2.imwrite(filename, gray)  # Now, we will save the image
    img = Image.open(filename)  # Open the processed image with pillow
    recognized_text = pytesseract.image_to_string(img).encode('utf-8')  # As a means of exceptions, need to read out as UTF-8, so no encoding errors would occur
    os.remove(filename)  # Deleting all temporary image
    os.remove(meme_name)
    return recognized_text  # Returns the recognized text in UTF-8 encodign and with capital and lower letters 
Example #30
Source File: CVTransforms.py    From ext_portrait_segmentation with MIT License 5 votes vote down vote up
def __call__(self, image, label):
        if random.random() < set_ratio:
            return image, label

        select = random.random()
        if select < 0.3:
            kernalsize = random.choice([3, 5])
            image = cv2.GaussianBlur(image, (kernalsize, kernalsize), 0)
        elif select < 0.6:
            kernalsize = random.choice([3, 5])
            image = cv2.medianBlur(image, kernalsize)
        else:
            kernalsize = random.choice([3, 5])
            image = cv2.blur(image, (kernalsize, kernalsize))
        return image, label