Esempio n. 1
1
def cartoon(srcColor):
    srcGray=cv2.cvtColor(srcColor,cv2.COLOR_BGR2GRAY)
    print srcGray.shape,srcColor.shape
    cv2.medianBlur(srcGray,5,srcGray)

    mask=srcGray.copy().astype(np.uint8)
    edges=srcGray.copy().astype(np.uint8)

    ### sketch detection
    cv2.Laplacian(srcGray,cv2.CV_8U,edges,5)
    cv2.threshold(edges,60,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU,mask)
    outImg=srcColor.copy()
    tmp=outImg.copy()

    ### bilateral filtering ###
    rep=10
    for i in xrange(rep):
        size=9;sigmaColor=9;sigmaSpace=7

        cv2.bilateralFilter(outImg,size,sigmaColor,sigmaSpace,tmp)
        cv2.bilateralFilter(tmp,size,sigmaColor,sigmaSpace,outImg)

    output=cv2.bitwise_and(srcColor,srcColor,mask=mask)
    cv2.edgePreservingFilter(output,output)

    return output
def main():

    # 動画の読み込み
    # cap = cv2.VideoCapture('IMG_3984.mp4')
    cap = cv2.VideoCapture('privacy.wmv')

    # 動画終了まで繰り返し
    while (cap.isOpened()):
        # フレーム取得
        ret, frame = cap.read()
        if ret == True:
            # フレームの速度計測
            t = time.time()
            frame = cv2.edgePreservingFilter(frame,
                                             flags=1,
                                             sigma_s=80,
                                             sigma_r=0.4)
            print('[INFO] elapsed time: {:.4f}'.format(time.time() - t))
        # フレームを表示
        cv2.imshow("edgePreserving", frame)

        # qキーが押されたら途中終了
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()
Esempio n. 3
0
def cartoonizeStyle1(sig_r=0.4, sig_s=50):
    global img_result
    imgToCartoon = img.copy()
    gray = cv2.cvtColor(imgToCartoon, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (3, 3), 0)
    edged = cv2.Laplacian(gray, -1, ksize=5)

    edged = 255 - edged
    edgedPreserve = cv2.edgePreservingFilter(imgToCartoon,
                                             flags=2,
                                             sigma_s=sig_s,
                                             sigma_r=sig_r)
    img_result = cv2.bitwise_and(edgedPreserve, edgedPreserve, mask=edged)
    img_result = cv2.GaussianBlur(img_result, (3, 3), 0)
    img_result = cv2.medianBlur(img_result, 3)
    #cv2.imshow("resultat2",result)
    #cv2.imwrite("results/t33.jpg",result)
    preview = img_result.copy()
    preview = cv2.resize(
        preview, (300, int((300 / img_result.shape[1]) * img_result.shape[0])),
        0, 0, cv2.INTER_NEAREST)
    preview = cv2.cvtColor(preview, cv2.COLOR_BGR2RGB)
    preview = Image.fromarray(preview)
    preview = ImageTk.PhotoImage(preview)
    Frame2.configure(image=preview)
    Frame2.image = preview
def cartoon(img):
    edges1 = cv2.bitwise_not(cv2.Canny(img, 100, 200))
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.medianBlur(gray, 5)
    dst = cv2.edgePreservingFilter(img, flags=2, sigma_s=64, sigma_r=0.25)
    cartoon1 = cv2.bitwise_and(dst, dst, mask=edges1)
    return cartoon1
Esempio n. 5
0
def cartoon():
    image = cv2.imread(x)[:, :, ::-1]
    global count, eimg
    count = 4
    if image is None:
        print("can not find image")
        exit()
    image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    image_gray = cv2.GaussianBlur(image_gray, (3, 3), 0)
    image_edge = cv2.Laplacian(image_gray, -1, ksize=5)
    image_edge = 255 - image_edge
    ret, image_edge = cv2.threshold(image_edge, 150, 255, cv2.THRESH_BINARY)
    edgePreservingImage = cv2.edgePreservingFilter(image,
                                                   flags=2,
                                                   sigma_s=50,
                                                   sigma_r=0.4)
    global o4
    output = np.zeros(image_gray.shape)
    output = cv2.bitwise_and(edgePreservingImage,
                             edgePreservingImage,
                             mask=image_edge)
    o4 = cv2.convertScaleAbs(output, alpha=1, beta=60)
    image = Image.fromarray(o4)
    eimg = image
    image = ImageTk.PhotoImage(image)
    panelB.configure(image=image)
    panelB.image = image
Esempio n. 6
0
def image_processing(img, filters):
    filters = [{
        'name': 'threshold',
        'color': 'GRAY',
        'low_tone': 0,
        'high_tone': 255,
        'type': ['THRESH_OTSU', 'THRESH_BINARY_INV'],
    }, {
        'name': 'gaussian_blur',
        'width': 3,
        'height': 3,
        'sigmax': 0
    }, {
        'name': 'edge_pre_serv'
    }]
    for f in filters:
        if f['name'] == 'gaussian_blur':
            w, h, s = f['width'], f['height'], f['sigmax']
            img = cv2.GaussianBlur(img, (w, h), s)

        elif f['name'] == 'threshold':
            l, h = f['low_tone'], f['high_tone']
            _type = sum([getattr(cv2, x) for x in f['type']])
            img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            img = cv2.threshold(img, l, h, _type)[1]

        elif f['name'] == 'edge_pre_serv':
            img = cv2.edgePreservingFilter(img)
    return img
Esempio n. 7
0
 def ice_blue(self):
     new_image = cv2.applyColorMap(self.image, cv2.COLORMAP_OCEAN)
     new_image = cv2.edgePreservingFilter(new_image,
                                          flags=1,
                                          sigma_s=70,
                                          sigma_r=0.5)
     return new_image
Esempio n. 8
0
    def generate_skin(self, img):
        """genrate skin table"""
        rows, cols, channels = img.shape
        current_img = copy.deepcopy(img)  # get img data
        current_img = cv2.edgePreservingFilter(img,
                                               flags=1,
                                               sigma_s=50,
                                               sigma_r=0.5)
        skin_table = np.ones(img.shape, np.uint8)  # get data is 0 matrix
        # self.skin_table = copy.deepcopy(self.current_img)
        # Skin is identified by pixels
        for r in range(rows):
            for c in range(cols):
                # get pixel value
                B = img.item(r, c, 0)
                G = img.item(r, c, 1)
                R = img.item(r, c, 2)
                # non-skin area if skin equals 0, skin area equals 1.
                if (abs(R - G) > 15) and (R > G) and (R > B):
                    if (R > 95) and (G > 40) and (B > 20) and (
                            max(R, G, B) - min(R, G, B) > 15):
                        pass
                    elif (R > 220) and (G > 210) and (B > 170):
                        pass
                else:
                    skin_table.itemset((r, c, 2), 0)
                    skin_table.itemset((r, c, 1), 0)
                    skin_table.itemset((r, c, 0), 0)

        return skin_table
Esempio n. 9
0
    def __init__(self, imdb):
        self.imdb = imdb

        # all filters
        self.filters = odict([
            ('Background Subtraction (mean)',
             imdb.pipeline().use_window().single_bgsub3(method='mean')),
            ('Background Subtraction (median)',
             imdb.pipeline().use_window().single_bgsub3(method='median')),
            ('Background Subtraction (min)',
             imdb.pipeline().use_window().single_bgsub3(method='min')),
            ('Background Subtraction (max)',
             imdb.pipeline().use_window().single_bgsub3(method='mean')),
            ('Original', imdb.pipeline()),
            ('Greyscale', imdb.pipeline().grey()),
            ('Edges', imdb.pipeline().grey().pipe(
                lambda im: cv2.Laplacian(im, cv2.CV_64F)).invert()),

            # https://www.learnopencv.com/non-photorealistic-rendering-using-opencv-python-c/
            ('Stylization', imdb.pipeline().pipe(
                lambda im: cv2.stylization(im, sigma_s=10, sigma_r=0.4))),
            ('Pencil Sketch', imdb.pipeline().pipe(lambda im: cv2.pencilSketch(
                im, sigma_s=10, sigma_r=0.1, shade_factor=0.02)[1])),
            ('Detail Enhance', imdb.pipeline().pipe(
                lambda im: cv2.detailEnhance(im, sigma_s=20, sigma_r=0.15))),
            ('Edge Preserving',
             imdb.pipeline().pipe(lambda im: cv2.edgePreservingFilter(
                 im, flags=1, sigma_s=30, sigma_r=0.4))),
        ])

        for name in self.filters:
            self.filters[name].fake_crop()
Esempio n. 10
0
def makeCartoon(original):

    # Make a copy of the origianl image to work with
    img = np.copy(original)

    # Convert image to grayscale
    imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Apply gaussian filter to the grayscale image
    imgGray = cv2.GaussianBlur(imgGray, (3, 3), 0)

    # Detect edges in the image and threshold it
    edges = cv2.Laplacian(imgGray, cv2.CV_8U, ksize=5)
    edges = 255 - edges
    ret, edgeMask = cv2.threshold(edges, 150, 255, cv2.THRESH_BINARY)

    # Apply Edge preserving filter to get the heavily blurred image
    imgBilateral = cv2.edgePreservingFilter(img,
                                            flags=2,
                                            sigma_s=50,
                                            sigma_r=0.4)

    # Create a outputmatrix
    output = np.zeros(imgGray.shape)

    # Combine the cartoon and edges
    output = cv2.bitwise_and(imgBilateral, imgBilateral, mask=edgeMask)

    return output
Esempio n. 11
0
 def cyberpunk_neon(self):
     new_image = cv2.applyColorMap(self.image, cv2.COLORMAP_PLASMA)
     new_image = cv2.edgePreservingFilter(new_image,
                                          flags=1,
                                          sigma_s=60,
                                          sigma_r=0.4)
     return new_image
Esempio n. 12
0
def dehaze(I,
           tmin=0.1,
           w=15,
           alpha=0.4,
           omega=0.75,
           p=0.1,
           eps=1e-3,
           reduce=False):
    m, n, _ = I.shape
    Idark, Ibright = get_illumination_channel(I, w)
    A = get_atmosphere(I, Ibright, p)

    init_t = get_initial_transmission(A, Ibright)
    if reduce:
        init_t = reduce_init_t(init_t)
    corrected_t = get_corrected_transmission(I, A, Idark, Ibright, init_t,
                                             alpha, omega, w)

    normI = (I - I.min()) / (I.max() - I.min())
    refined_t = guided_filter(normI, corrected_t, w, eps)
    J_refined = get_final_image(I, A, refined_t, tmin)

    enhanced = (J_refined * 255).astype(np.uint8)
    f_enhanced = cv2.detailEnhance(enhanced, sigma_s=10, sigma_r=0.15)
    f_enhanced = cv2.edgePreservingFilter(f_enhanced,
                                          flags=1,
                                          sigma_s=64,
                                          sigma_r=0.2)
    return f_enhanced
Esempio n. 13
0
def enmascaradoPiola(img):
    #Etapa uno, suavizar fondo e interior de las hojas preservado bordes
    imgBlur = cv.edgePreservingFilter(img, flags=1, sigma_s=50, sigma_r=0.4)

    #Deformo los colores preservando solo los bordes, dando un efecto de acuarela, lo q realza el borde
    imgAc = cv.stylization(imgBlur, sigma_s=200, sigma_r=0.7)

    #Paso a escala de grises
    imgGray = cv.cvtColor(imgAc, cv.COLOR_BGR2GRAY)

    #Filtrado para suavizar mas el fondo
    imgG = cv.GaussianBlur(imgGray, (5, 5), 0.5)

    #Expansion de bordes por dilatacion
    ee = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))
    imgDil = cv.morphologyEx(imgG, cv.MORPH_DILATE, ee, iterations=1)

    #Hago un filtrado de promedio para eliminar bordes internos de la hoja debido a la textura
    img1Fil = cv.boxFilter(imgDil, -1, (5, 5))

    #Binarizo con thresh adaptativo
    img1Bin = cv.adaptiveThreshold(img1Fil, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C,
                                   cv.THRESH_BINARY, 11, 1)

    #Busqueda y dibujo de contornos
    imgContornos = img.copy()
    contours, _ = cv.findContours(img1Bin, cv.RETR_EXTERNAL,
                                  cv.CHAIN_APPROX_NONE)  #Contornos externos
    cv.drawContours(imgContornos, contours, -1, (0, 0, 255), 2)

    return contours
Esempio n. 14
0
def rendering(image):
    dst = cv2.edgePreservingFilter(image, flags=1, sigma_s=100, sigma_r=1.3)
    
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 10))
    dst2 = cv2.erode(dst,kernel)
     
    return dst2
def edge_preserve(current_img, value=None):
    if value is None:
        value = np.random.random() * 4 + 1
    value = value * 0.05
    return cv2.edgePreservingFilter(current_img,
                                    flags=1,
                                    sigma_s=50,
                                    sigma_r=value)
Esempio n. 16
0
 def sweet_dreams(self):
     new_image = cv2.applyColorMap(self.image,
                                   cv2.COLORMAP_TWILIGHT_SHIFTED)
     new_image = cv2.edgePreservingFilter(new_image,
                                          flags=1,
                                          sigma_s=40,
                                          sigma_r=0.6)
     return new_image
Esempio n. 17
0
def edge_preserving(A):
    B = np.zeros((A.shape), dtype=np.float32)
    for i in range(A.shape[0]):
        B[i, :, :, :] = cv2.edgePreservingFilter(A[i, :, :, :],
                                                 flags=1,
                                                 sigma_s=30,
                                                 sigma_r=0.6)
    return B
Esempio n. 18
0
 def edgePreserve(self, flags=1, sigma_s=50, sigma_r=0.15):
     '''
     flags: 边缘保持方法(迭代比归一化快), 1 -> 迭代滤波, 2 -> 归一化
     '''
     out = cv2.edgePreservingFilter(self.img,
                                    flags=1,
                                    sigma_s=50,
                                    sigma_r=0.15)
     self.showImage("edgePreservingFilter.png", out)
Esempio n. 19
0
 def edge_preserve(self):
     if self.raw_image is None:
         return 0
     if self.ui.horizontalSlider_3.value() == 0:
         self.current_img = self.raw_image
         self.show_image()
         return 0
     value = self.ui.horizontalSlider_3.value() * 0.05
     self.current_img = cv2.edgePreservingFilter(self.current_img, flags=1, sigma_s=50, sigma_r=value)
Esempio n. 20
0
def find_contours(filepath,
                  contour_len_thresh=3,
                  nlevels=10,
                  min_val=20,
                  max_val=255,
                  resize_to=None):
    if not isfile(filepath):
        raise FileExistsError(f'Image file [{filepath}] does not exist')

    im = cv2.imread(filepath)

    scaled = im
    if resize_to is not None:
        h, w, c = im.shape
        ratio = w / resize_to
        new_size = tuple(
            [int(round(v / ratio)) for v in [im.shape[1], im.shape[0]]])
        scaled = cv2.resize(im, new_size)

    dst = cv2.edgePreservingFilter(scaled, sigma_s=20, sigma_r=0.95)

    imgray = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(imgray, (9, 9), 0)

    # FIND CONTOURS
    contours_all = []
    layers_all = []
    threshvals = np.linspace(min_val, max_val, num=nlevels, dtype=np.int)
    for t in threshvals:
        ret, thresh = cv2.threshold(blur, t, 255, 0)
        contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,
                                               cv2.CHAIN_APPROX_SIMPLE)
        order = [
            v for i in sorted(set(hierarchy[0, :, 3]))
            for v in np.where(hierarchy[0, :, 3] == i)[0]
        ]
        layers = (hierarchy[0, :, 3] + 1) + (hierarchy[0, :, 0] + 1)
        contours_all.extend([contours[i] for i in order])
        layers_all.extend(layers)

    if not len(contours_all):
        raise NoContoursFound(
            f'Failed to find contours in image file [{filepath}]')

    #merged        = list( zip(contours_all, layers_all))
    #merged_sorted = sorted( merged, key = lambda m: m[1], reverse = False )
    #contours_all  = [ m[0] for m in merged_sorted ]
    #contours_all  =
    fcnt = [c for c in contours_all if len(c) > contour_len_thresh]

    if not len(contours_all):
        raise NoContoursFound(
            f'Failed to find contours with len > {contour_len_thresh} in image file [{filepath}]'
        )

    return dst, fcnt
def test_dt():
    img = io.imread('../images/cow.jpg') / 255.0
    original = np.copy(img)
    # the opencv function
    dst = cv2.edgePreservingFilter(src, flags=1, sigma_s=60, sigma_r=0.4)
    # typ =np.info(img.dtype).max  #in case of a binary image
    img = img.astype(np.float32)
    img_bilateral = cv2.bilateralFilter(img, 5, 50, 50)
    denoised_img = denoise(img)
    show_images([img, img_bilateral, denoised_img])
Esempio n. 22
0
def main():
    src = cv.imread("../../pic/IMG_20191204_151110.jpg")
    cv.namedWindow("src", cv.WINDOW_AUTOSIZE)
    cv.imshow("src", src)
    dst = cv.edgePreservingFilter(src,
                                  sigma_s=100,
                                  sigma_r=0.4,
                                  flags=cv.RECURS_FILTER)
    cv.imshow("dst", dst)
    cv.waitKey(0)
    cv.destroyAllWindows()
Esempio n. 23
0
 def cartoon(self):
     img = self.image
     edges1 = cv2.bitwise_not(cv2.Canny(img, 100, 200))
     gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
     gray = cv2.medianBlur(gray, 5)
     edges2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
                                    cv2.THRESH_BINARY, 7, 7)
     dst = cv2.edgePreservingFilter(img, flags=2, sigma_s=64, sigma_r=0.25)
     cartoon1 = cv2.bitwise_and(dst, dst, mask=edges1)
     cartoon2 = cv2.bitwise_and(dst, dst, mask=edges2)
     return cartoon2
Esempio n. 24
0
    def __init__(self, Canvas, window_title, AskLayerNames=True, CorrectXYWhileSelecting=True, RegionMovable=True):
        super().__init__(Canvas, window_title, AskLayerNames=AskLayerNames, CorrectXYWhileSelecting=CorrectXYWhileSelecting, RegionMovable=RegionMovable)

        # Tolerance value to be used
        self.Tolerance = 32
        # Seed point coordinates
        self.seed = None
        # Mask image of the selected region
        self.Mask = np.zeros((self.CanvasShape[0], self.CanvasShape[1], 1), dtype=np.uint8)
        # Image to be worked on
        self.WorkingImage = cv2.edgePreservingFilter(self.CombinedFrame.copy(), flags=1, sigma_s=11, sigma_r=0.2)
        self.WorkingImage = cv2.cvtColor(self.WorkingImage, cv2.COLOR_BGR2GRAY)
Esempio n. 25
0
        def transform(self, renderer_type_id):
            print("transform {}".format(renderer_type_id))
            try:
                src_image = self.get_opencv_image()
                self.transformed_image = None

                if src_image.any() != None:
                    if renderer_type_id == MainView.EdgePreserveSmoothingByNormalizedConvolutionFilter:
                        self.transformed_image = cv2.edgePreservingFilter(
                            src_image, flags=1)

                    if renderer_type_id == MainView.EdgePreserveSmoothingByRecursiveFilter:
                        self.transformed_image = cv2.edgePreservingFilter(
                            src_image, flags=2)

                    if renderer_type_id == MainView.DetailEnhancement:
                        self.transformed_image = cv2.detailEnhance(src_image)

                    if renderer_type_id == MainView.MonochromePencilSketch:
                        self.transformed_image, _ = cv2.pencilSketch(
                            src_image,
                            sigma_s=10,
                            sigma_r=0.1,
                            shade_factor=0.03)

                    if renderer_type_id == MainView.ColorPencilSketch:
                        _, self.transformed_image = cv2.pencilSketch(
                            src_image,
                            sigma_s=10,
                            sigma_r=0.1,
                            shade_factor=0.03)

                    if renderer_type_id == MainView.Stylization:
                        self.transformed_image = cv2.stylization(src_image)

                    if self.transformed_image.all() != None:
                        self.set_opencv_image(self.transformed_image)
                        self.update()
            except:
                traceback.print_exc()
Esempio n. 26
0
        def filter(self, sigmaColor, sigmaSpace):

            if self.source_image.all() != None:
                flag = cv2.RECURS_FILTER

                filtered_image = cv2.edgePreservingFilter(
                    self.source_image,
                    flag,
                    sigma_s=sigmaSpace,
                    sigma_r=float(sigmaColor) / 100.0)

                self.set_opencv_image(filtered_image)
                self.update()
Esempio n. 27
0
def main(args):

    image_in = cv2.imread(args.fname_input)
    image_out = cv2.edgePreservingFilter(image_in)
    image_out, _ = cv2.pencilSketch(image_out, sigma_r=0.09, shade_factor=0.05)

    if args.visualize:
        image_out = cv2.cvtColor(image_out, cv2.COLOR_GRAY2RGB)
        image_both = np.hstack((image_in, image_out))
        cv2.imshow('Pencil sketch', image_both)
        cv2.waitKey(0)

    cv2.imwrite(args.fname_output, image_out)
Esempio n. 28
0
def find_contours_canny(filepath,
                        contour_len_thresh=5,
                        nlevels=10,
                        min_val=20,
                        max_val=255,
                        resize_to=None,
                        remove_duplicates=False):
    if not isfile(filepath):
        raise FileExistsError(f'Image file [{filepath}] does not exist')

    im = cv2.imread(filepath)

    scaled = im
    if resize_to is not None:
        h, w, c = im.shape
        ratio = w / resize_to
        new_size = tuple(
            [int(round(v / ratio)) for v in [im.shape[1], im.shape[0]]])
        scaled = cv2.resize(im, new_size)

    # Filter to generate color regions
    blur_bgr = cv2.edgePreservingFilter(scaled, sigma_s=20, sigma_r=0.95)
    # blur_bgr = cv2.stylization(im, sigma_s=20, sigma_r=0.95)

    imgray = cv2.cvtColor(blur_bgr, cv2.COLOR_BGR2GRAY)

    kernel = np.ones((3, 3), np.uint8)
    threshvals = np.linspace(min_val, max_val, num=nlevels, dtype=np.int)
    layered = np.zeros(imgray.shape)

    for i, t in enumerate(threshvals):
        ret, thresh = cv2.threshold(imgray, t, min(250, t + 100), 0)
        canny = cv2.Canny(thresh, t, min(250, t + 100))
        ret, thresh = cv2.threshold(canny, t, 255, 0)
        layered = np.array(np.clip(layered + thresh, 0, 255), dtype=np.uint8)
        layered = cv2.GaussianBlur(layered, (1, 1), 0)
        layered = cv2.morphologyEx(layered, cv2.MORPH_CLOSE, kernel)

    # Morphology and some blurring to clean the lines
    layered = cv2.GaussianBlur(layered, (3, 3), 0)
    layered = cv2.morphologyEx(layered, cv2.MORPH_OPEN, kernel)
    layered = cv2.morphologyEx(layered, cv2.MORPH_CLOSE, kernel)

    contours, hierarchy = cv2.findContours(layered, cv2.RETR_TREE,
                                           cv2.CHAIN_APPROX_SIMPLE)

    if not len(contours):
        raise NoContoursFound(
            f'Failed to find contours in image file [{filepath}]')

    return blur_bgr, contours
Esempio n. 29
0
def _cartoon(orig):
    img = np.copy(orig)
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img_gray = cv2.GaussianBlur(img_gray, (3, 3), 0)
    edges = cv2.Laplacian(img_gray, cv2.CV_8U, ksize=5)
    edges = 255 - edges
    ret, edge_mask = cv2.threshold(edges, 150, 255, cv2.THRESH_BINARY)
    img_bilateral = cv2.edgePreservingFilter(img,
                                             flags=2,
                                             sigma_s=50,
                                             sigma_r=0.4)
    output = np.zeros(img_gray.shape)
    output = cv2.bitwise_and(img_bilateral, img_bilateral, mask=edge_mask)
    return output
Esempio n. 30
0
def edge_detection(img_grabcut):

    gray = cv2.cvtColor(img_grabcut, cv2.COLOR_BGR2GRAY)
    _, gray = cv2.threshold(gray, 120, 255, cv2.THRESH_TOZERO)
    gray = cv2.GaussianBlur(gray, (7, 7), 0)
    gray = cv2.bilateralFilter(gray, 9, 75, 75)
    gray = cv2.edgePreservingFilter(gray, flags=1, sigma_s=45, sigma_r=0.2)

    edged = cv2.Canny(gray, 75, 200, True)

    #cv2.imshow("grayscale", gray)
    cv2.imshow("edged", edged)

    return edged
Esempio n. 31
0
async def hehe(event):
    if not event.reply_to_msg_id:
        await event.reply("Reply to any Image.")
        return   
    reply = await event.get_reply_message()
    await event.edit('`Processing...`')
    image = await bot.download_media(reply.media, path)
    img = cv2.VideoCapture(image) 
    ret, frame = img.read() 
    smooth = cv2.edgePreservingFilter(frame, flags=1, sigma_s=60, sigma_r=0.4)
    cv2.imwrite("danish.jpg", smooth)
    await event.client.send_file(event.chat_id, "danish.jpg", force_document=False, reply_to=event.reply_to_msg_id)
    await event.delete()
    shutil.rmtree(path)
    os.remove("danish.jpg")
Esempio n. 32
0
'''
OpenCV Non-Photorealistic Rendering Python Example

Copyright 2015 by Satya Mallick <*****@*****.**>
'''

import cv2

# Read image
im = cv2.imread("cow.jpg");

# Edge preserving filter with two different flags.
imout = cv2.edgePreservingFilter(im, flags=cv2.RECURS_FILTER);
cv2.imwrite("edge-preserving-recursive-filter.jpg", imout);

imout = cv2.edgePreservingFilter(im, flags=cv2.NORMCONV_FILTER);
cv2.imwrite("edge-preserving-normalized-convolution-filter.jpg", imout);

# Detail enhance filter
imout = cv2.detailEnhance(im);
cv2.imwrite("detail-enhance.jpg", imout);

# Pencil sketch filter
imout_gray, imout = cv2.pencilSketch(im, sigma_s=60, sigma_r=0.07, shade_factor=0.05);
cv2.imwrite("pencil-sketch.jpg", imout_gray);
cv2.imwrite("pencil-sketch-color.jpg", imout);

# Stylization filter
cv2.stylization(im,imout);
cv2.imwrite("stylization.jpg", imout);
def sketch_img(img):
    # outimg = cv2.stylization(img, sigma_s=60, sigma_r=0.07)
    outimg = cv2.edgePreservingFilter(img, flags=1, sigma_s=60, sigma_r=0.4)
    outimg = cv2.detailEnhance(outimg, sigma_s=10, sigma_r=0.15)
    dst_gray, dst_color = cv2.pencilSketch(outimg, sigma_s=60, sigma_r=0.07, shade_factor=0.05)
    return dst_gray