Esempio n. 1
0
def smoothing_btn_func():
    global temp,mod,HSI_arr
    if(mode.get()==1):  #HSI
        temp=Image.fromarray(np.uint8(HSI_arr))
    else:
        temp=mod #RGB
    temp = temp.filter(ImageFilter.Kernel((5,5),(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))) #kernel
    refresh()
Esempio n. 2
0
 def tranfun(self, image):
     image = get_pil_image(image)
     angle=random.randint(0,self.angle)
     M = cv2.getRotationMatrix2D((self.degree / 2, self.degree / 2), angle, 1)
     motion_blur_kernel = np.diag(np.ones(self.degree))
     motion_blur_kernel = cv2.warpAffine(motion_blur_kernel, M, (self.degree, self.degree))
     motion_blur_kernel = motion_blur_kernel / self.degree
     image = image.filter(ImageFilter.Kernel(size=(self.degree,self.degree),kernel=motion_blur_kernel.reshape(-1)))
     return image
Esempio n. 3
0
def sharp_func(val):
    global mod, temp
    val = int(val)
    temptemp = mod.copy()  #same as sharp func
    for i in range(val):
        temptemp = temptemp.filter(
            ImageFilter.Kernel((3, 3), (0, -1, 0, -1, 5, -1, 0, -1, 0)))
    temp = temptemp
    refresh()
Esempio n. 4
0
def smooth_func(val):
    global mod, temp
    val = int(val)
    temptemp = mod.copy()  #iterate times
    for i in range(val):
        temptemp = temptemp.filter(
            ImageFilter.Kernel((3, 3), (1, 2, 1, 2, 4, 2, 1, 2, 1)))  #filter
    temp = temptemp
    refresh()
def kernel1_image(im):
    size = (3, 3)
    kernel1 = [1, 1, 1, 1, -1, 1, -1, -1, -1]
    ker1 = ImageFilter.Kernel(size, kernel1, scale=None, offset=0)
    # plt.subplot(3, 4, 11)
    im11 = im.filter(ker1)
    plt.show(im11)
    plt.title("Custom Filter 1") 
    plt.show()
def suavizado():
    
    imagen_original = Image.open(fbi)
    tamaño = (3,3)
    a=1
    coeficientes= [a, a, a, a, a, a, a, a, a]
    imagen_filtrada = imagen_original.filter(ImageFilter.Kernel(tamaño, coeficientes))    
    
    return imagen_original.show(),imagen_filtrada.show()
Esempio n. 7
0
    def test_consistency_5x5(self):
        im = Image.open("Tests/images/hopper.bmp")
        emboss = im.filter(
            ImageFilter.Kernel(
                (5, 5), (-1, -1, -1, -1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1,
                         -1, 0, 1, 1, 1, 0, 1, 1, 1, 1), 0.3))

        self.assert_image_equal(
            emboss, Image.open("Tests/images/hopper_emboss_more.bmp"))
Esempio n. 8
0
    def vivid(self, image):  # 선명하게 clear!
        mat = ImageFilter.Kernel(
            (3, 3), (0, -1 / 2, 0, -1 / 2, 3, -1 / 2, 0, -1 / 2, 0))
        image = image.filter(mat)
        pixmap = QPixmap.fromImage((ImageQt.ImageQt(image)))
        pixmap.detach()
        return (image, pixmap)

        pass
Esempio n. 9
0
 def procesa_imagen(self, tam_matriz):
     if self.aplicacion.imagen != None:
         L = self.asigna_valores_filtro(tam_matriz)
         imgf = Image.fromarray(self.aplicacion.imagen)
         img_aux = imgf.filter(ImageFilter.Kernel(L[0], L[1], L[2]))
         self.aplicacion.imagen = numpy.asarray(img_aux)
         self.aplicacion.dibujar_img(self.aplicacion.imagen)
         self.desaparece_dialogo()
         self.aplicacion.actualiza_historial()
def kernel2_image(im):
    size = (3, 3)
    kernel2 = [1, 0, -1, 1, 0, -1, 0, 0, -1]
    ker2 = ImageFilter.Kernel(size, kernel2, sale=None, offset=0)
    plt.subplot(3, 5, 12)
    im12 = im.filter(ker2)
    plt.imshow(im12)
    plt.title("Custom Filter 2")
    plt.show()
def main():
    image = Image.open('../lenna.png')
    image.show('Original')

    # Using kernels for blurring
    # The size of the kernel - can be 3x3 or 5x5
    size = (3, 3)
    # The kernel itself
    kernel_matrix = (1, 1, 1,
                     1, 1, 1,
                     1, 1, 1)
    # The final convolved result for each pixel is divied by the scale argument
    # By default it is the sum of the kernel matrix weights.
    # In our case the sum is 9. Each pixel is a result of convolving
    # the neighbour pixels with the kernel matrix and then dividing it by 9.
    # In other words - it is the mean value of the 3x3 window for each pixel
    # thus resulting in a blurred image.
    kernel = ImageFilter.Kernel(size, kernel_matrix)
    blurred_image = image.filter(kernel)
    blurred_image.show('Blur')

    # Let's smooth the image
    kernel_matrix = (1, 1, 1,
                     1, 5, 1,
                     1, 1, 1)
    kernel = ImageFilter.Kernel(size, kernel_matrix)
    smooth_image = image.filter(kernel)
    smooth_image.show('Smooth')

    # Sharpening
    kernel_matrix = (-2, -2, -2,
                     -2, 32, -2,
                     -2, -2, -2)
    kernel = ImageFilter.Kernel(size, kernel_matrix, scale=16)
    sharpen_image = image.filter(kernel)
    sharpen_image.show('Sharpen')

    # Detail
    kernel_matrix = (0, -1, 0,
                     -1, 10, -1,
                     0, -1, 0)
    kernel = ImageFilter.Kernel(size, kernel_matrix, scale=6)
    detail_image = image.filter(kernel)
    detail_image.show('Detail')
Esempio n. 12
0
 def process_image(self, url):
     image = self._get_image(url)
     image.filter(ImageFilter.SHARPEN)
     image = self._resize_image(image, 12)
     image.filter(ImageFilter.GaussianBlur(2))
     image.filter(ImageFilter.SMOOTH)
     image.filter(ImageFilter.Kernel((3, 3),
                                     [1, 1, 1, 0, 0, 0, -1, -1, -1]))
     s = pytesseract.image_to_string(image)
     return self.normalize(s)
Esempio n. 13
0
 def auto_kernel(self, size):
     self.modal_window = Modal("Zdefiniuj maskę")
     self.modal_window.init_own_mask_modal(size)
     if self.modal_window.exec_():
         self.kernel_vals = self.modal_window.button_nonsignal_confirm_exit(
             "unsharp")
         kernel_img = self.image.filter(
             ImageFilter.Kernel(self.kernel_vals[0], self.kernel_vals[1]))
     self.image = kernel_img
     self.loadImageFromPIX(self.image)
Esempio n. 14
0
def kernelSmooth(sourceImagePath, targetImagePath):  #13th function extra
    im = Image.open(sourceImagePath)
    new = im.copy()
    new = new.filter(
        ImageFilter.Kernel((3, 3), [1, 2, 1, 2, 4, 2, 1, 2, 1], 16))
    if targetImagePath != "":
        new.save(targetImagePath)
        print("saved")
    else:
        return new
Esempio n. 15
0
File: pic.py Progetto: jeff82/nn
def readimg():
    im= img.filter(ImageFilter.SMOOTH)
    im=img.filter(ImageFilter.Kernel((3,3),(1,1,1,0,0,0,2,0,2)))
    #im.show()
    (W,H)=im.size
    pixel=numpy.zeros([W,H,4])
    for w in range(W):
        for h in range(H):
            pixel[w,h,(range(3))] = numpy.array(im.getpixel((w, h)) )
            pixel[w,h,0:3]=sum(pixel[w,h,range(3)])/3
    return pixel,img
Esempio n. 16
0
def find_edges(img):
    #img: image name
    Filter = (-1, -1, -1, -1, 8, -1, -1, -1, -1)
    img = Image.open(img)
    img = img.convert("L")
    # Calculating Edges with Laplace Kernel
    final = img.filter(ImageFilter.Kernel((3, 3), Filter, 1, 0))
    rgb_im = final.convert('RGB')
    matrix = np.array(rgb_im)
    #r, g, b = rgb_im.getpixel((1, 1))
    return matrix
def run():
    # Abrir a Imagem
    img1 = Image.open('images/originalNature.jpg')

    # Criar o Kernel (Sharpen)
    kernelS = ImageFilter.Kernel((3, 3), (0, -1, 0, -1, 5, -1, 0, -1, 0), 1, 0)

    # Aplicar o filtro na imagem
    img2 = img1.filter(kernelS)

    # Criar o Kernel (Blur
    kernelB = ImageFilter.Kernel(
        (3, 3), ((1 / 9), (1 / 9), (1 / 9), (1 / 9), (1 / 9), (1 / 9), (1 / 9),
                 (1 / 9), (1 / 9)), 1, 0)

    # Aplicar o filtro na imagem
    img3 = img2.filter(kernelB)

    # Salvar as imagens
    img2.save('images/filtro_sharpen.jpg')
    img3.save('images/filtro_sharpen_mediana.jpg')
Esempio n. 18
0
def Fauna():

    # Abrindo uma imagem
    img = Image.open("Foto/Imagem.jpg")


    #Quebra em canais
    #Faz um gausiano em cada canal
    #Aumenta o brilho em azul e verde, diminui em vermelho
    #junta tudo
    r,g,b = img.split()

    #Gaussiano
    k = [1,2,1,2,4,2,1,2,1]
    filtro = ImageFilter.Kernel((3,3),k)
    r = r.filter(filtro)
    g = g.filter(filtro)
    b = b.filter(filtro)

    #Equalizando a imagem
    r = ImageOps.equalize(r)
    g = ImageOps.equalize(g)
    b = ImageOps.equalize(b)

    #Brilho
    ref=[]
    lut=[]
    for i in range(256):
        ref.append(i)
        val = i+50
        if val>255: val=255
        if val<0: val=0
        lut.append(val)

    g = g.point(lut)
    b = b.point(lut)

    #Brilho
    ref=[]
    lut=[]
    for i in range(256):
        ref.append(i)
        val = i-50
        if val>255: val=255
        if val<0: val=0
        lut.append(val)

    r = r.point(lut)

    img = Image.merge('RGB', (r, g, b))
    img.save("Processadas/FiltroImagens.jpg")

    Fauna2.Fauna2()
Esempio n. 19
0
    def test_consistency_3x3(self):
        source = Image.open("Tests/images/hopper.bmp")
        reference = Image.open("Tests/images/hopper_emboss.bmp")
        kernel = ImageFilter.Kernel((3, 3), (-1, -1, 0, -1, 0, 1, 0, 1, 1), .3)
        source = source.split() * 2
        reference = reference.split() * 2

        for mode in ['L', 'LA', 'RGB', 'CMYK']:
            self.assert_image_equal(
                Image.merge(mode, source[:len(mode)]).filter(kernel),
                Image.merge(mode, reference[:len(mode)]),
            )
Esempio n. 20
0
def filtro02():
    # Abrir a Imagem
    img1 = Image.open('images/originalFachada.jpg')

    # Criar o Kernel
    kernel = ImageFilter.Kernel((3, 3), (0, 1, 0, 1, -4, 1, 0, 1, 0), 1, 0)

    # Aplicar o filtro na imagem
    img2 = img1.filter(kernel)

    # Salvar a imagem
    img2.save('images/filtro_2.jpg')
Esempio n. 21
0
def random_blur(img, prob):
    """
    Randomly blur an image.

    Args
    - img: (Pillow.Image)
    - prob: Probability to blur
    """
    if np.random.random() > prob:
        return img

    # TODO: stronger blur
    filters = [
        ImageFilter.BoxBlur(3),
        ImageFilter.GaussianBlur(3),
        ImageFilter.Kernel((5, 5), (1, 0, 0, 0, 0,
                                    0, 1, 0, 0, 0,
                                    0, 0, 1, 0, 0,
                                    0, 0, 0, 1, 0,
                                    0, 0, 0, 0, 1)),
        ImageFilter.Kernel((5, 5), (0, 0, 0, 0, 1,
                                    0, 0, 0, 1, 0,
                                    0, 0, 1, 0, 0,
                                    0, 1, 0, 0, 0,
                                    1, 0, 0, 0, 0)),
        ImageFilter.Kernel((5, 5), (0, 0, 0, 0, 0,
                                    0, 0, 0, 0, 0,
                                    1, 1, 1, 1, 1,
                                    0, 0, 0, 0, 0,
                                    0, 0, 0, 0, 0)),
        ImageFilter.Kernel((5, 5), (0, 0, 1, 0, 0,
                                    0, 0, 1, 0, 0,
                                    0, 0, 1, 0, 0,
                                    0, 0, 1, 0, 0,
                                    0, 0, 1, 0, 0)),
    ]

    img = img.filter(np.random.choice(filters))

    return img
Esempio n. 22
0
def apply_edge_detector(input_image):
    # Apply median filter with 3x3 window
    median_image = input_image.filter(ImageFilter.MedianFilter(3))

    # Apply 3x3 Sobel filters
    # Apply for X
    kernel_x = (-1, 0, 1, -2, 0, 2, -1, 0, 1)
    kernelx_image = median_image.filter(
        ImageFilter.Kernel((3, 3), kernel_x, scale=1))

    # Apply for Y
    kernel_y = (1, 2, 1, 0, 0, 0, -1, -2, -1)
    kernely_image = median_image.filter(
        ImageFilter.Kernel((3, 3), kernel_y, scale=1))

    # Sum the pixels of the X and Y sobel images
    merged = ImageChops.add(kernelx_image, kernely_image)

    # Thresholding
    merged = merged.point(lambda x: 0 if x < 60 else 255)

    return merged
Esempio n. 23
0
def apply_edge_detector(input_image):
    # Apply median filter with 3x3 window
    median_image = input_image.filter(ImageFilter.MedianFilter(3))

    # Apply 3x3 center difference filters
    # Apply for X
    kernel_x = (0, 0, 0, 1, 0, -1, 0, 0, 0)
    kernelx_image = median_image.filter(
        ImageFilter.Kernel((3, 3), kernel_x, scale=2))

    # Apply for Y
    kernel_y = (0, 1, 0, 0, 0, 0, 0, -1, 0)
    kernely_image = median_image.filter(
        ImageFilter.Kernel((3, 3), kernel_y, scale=2))

    # Sum the pixels of X and Y
    merged = ImageChops.add(kernelx_image, kernely_image)

    # Thresholding
    merged = merged.point(lambda x: 0 if x < 10 else 255)

    return merged
Esempio n. 24
0
def img_kernel(filename, size, kernel, scale=None, offset=None):
    im = get_img(filename)
    if scale is not None and scale.strip() != '':
        scale = float(scale)
    else:
        scale = None
    if offset is not None and offset.strip() != '':
        offset = float(offset)
    else:
        offset = 0
    im_filter = ImageFilter.Kernel(size, kernel, scale, offset)
    res = im.filter(im_filter)
    return save_img(res, filename)
Esempio n. 25
0
def sharpness(img):
    """Calculate the sharpness of the image using a Laplacian Kernel.

    """
    img_bw = img.convert('L')
    filtered = img_bw.filter(
        ImageFilter.Kernel(
            (3, 3),
            # Laplacian Kernel:
            (-1, -1, -1, -1, 8, -1, -1, -1, -1),
            1,
            0,
        ))
    return np.std(filtered)
Esempio n. 26
0
def filter_convolutional(image, kernel, size=(3,3), title=str()\
, xlabel=str(), ylabel=str(), is_show=False, extension='conv'):
    '''Apply convolutional filter over a PIL image using a kernel given as 
    parameter of this function.
    Image is converted into gray levels.
    Transformed image histogram may also be displayed.
    '''
    #---------------------------------------------------------------------------
    # Les filtres par convolution ne supportent que les formats RGB et L
    # d'encodage des pixels. L'image est réencodée en L
    #---------------------------------------------------------------------------
    image_L = Image.fromarray(np.array(image)).convert('L')

    #---------------------------------------------------------------------------
    # Construction du filtre avec le notau pré-définie
    #---------------------------------------------------------------------------
    image_filtered = ImageFilter.Kernel(size,
                                        kernel.flatten(),
                                        scale=None,
                                        offset=0)

    #---------------------------------------------------------------------------
    # Filtrage appliqué a l'image
    #---------------------------------------------------------------------------
    image_filtered = image_L.filter(image_filtered)

    #---------------------------------------------------------------------------
    # L'histograme des pixels et des pixels cumulés est affiché
    #---------------------------------------------------------------------------
    image_hist(image_filtered, title=title, xlabel=xlabel, ylabel=ylabel)

    image_hist(image_filtered\
               , title=title+' cumulé'\
               , xlabel=xlabel\
               , ylabel=ylabel+" cumulés"\
              ,cumulative=True)
    #---------------------------------------------------------------------------
    # Sauvegarde de l'image filtree dans un fichier
    #---------------------------------------------------------------------------
    filename = "./data/image_filtered_conv_" + extension + ".png"
    image_filtered.save(filename)

    #---------------------------------------------------------------------------
    # L'histograme des pixels et des pixels cumulés est affiché
    #---------------------------------------------------------------------------
    if is_show is True:
        image_filtered.show()

    return filename, image_filtered
Esempio n. 27
0
 def custom(self, **kwargs):
     params = kwargs['params']
     kernel = tuple(map(int, params['kernel'].split(' ')))
     if 'scale' in params.keys():
         scale = int(params['scale'])
     else:
         scale = 1
     if 'offset' in params.keys():
         offset = int(params['offset'])
     else:
         offset = 0
     n = int(len(kernel)**0.5)
     f = ImageFilter.Kernel((n, n), kernel, scale, offset)
     self.final = self.img.filter(f)
     self.filter = "custom"
Esempio n. 28
0
def filter(image_matrix, effect):

    image_object = Image.fromarray(image_matrix)

    # define sharpen and blur kernels
    sharpen_kernel = np.asarray([0, -1 / 3, 0, -1 / 3, 3, -1 / 3, 0, -1 / 3, 0])
    blur_kernel = np.asarray([1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9, 1 / 9])
    unsharp_mask_kernel = (-1 / 256) * np.asarray([1, 4, 6, 4, 1, 4, 16, 24, 16, 4, 6, 24, -476, 24, 6, 4, 16, 24, 16, 4, 1, 4, 6, 4, 1])

    # convolve with kernels
    if effect == 'sharpen':
        img_sharpen = image_object.filter(ImageFilter.Kernel((3, 3), sharpen_kernel, scale=None))
        final_img = img_sharpen

    elif effect == 'blur':
        img_blur = image_object.filter(ImageFilter.Kernel((3, 3), blur_kernel, scale=None))
        final_img = img_blur

    elif effect == 'unsharp':
        img_unsharp = image_object.filter(ImageFilter.Kernel((5, 5), unsharp_mask_kernel, scale=None))
        final_img = img_unsharp

    # return an image object of the filtered image, which can be feedback into the input again
    return np.asarray(final_img)
Esempio n. 29
0
def remove_specks_or_blur(X):
    """This attempts to reduce the noise introduced in
       the later pages that are harder to read.
       It does this by attempting to make any black pixel
       white that does not have enough black neighbour pixels.

       Alternatively, it applies blurring to the image.

    Params:
    X - feature vectors stored as rows in a matrix
    """
    speck_removal_convolution = (
    1, 1, 1,
    1, 1, 1,
    1, 1, 1
    )

    convolution = ImageFilter.Kernel(
    size=(3,3),
    kernel=speck_removal_convolution,
    scale=9,
    offset=0
    )

    # Apply to each letter individually
    for i in range(len(X)):

        # Reshape the feature vector to image dimensions and convert the object
        # to a Pil Image
        rectangular_image_array = np.reshape(X[i,:], NEW_DIMENSIONS_2D)
        image = Image.fromarray(rectangular_image_array)
        image = image.convert("L")

        if APPLY_BLURRING:
            image = image.filter(GaussianBlur(radius=2))
            #image = image.filter(ImageFilter.BLUR)

        elif APPLY_SPECK_REMOVAL:
            image = image.filter(convolution)

        # Convert the Pil Image back to a numpy feature vector
        image_array = np.array(image)
        image_array = np.reshape(image_array, (NEW_DIMENSIONS,))
        X[i,:] = image_array

    return X
Esempio n. 30
0
def sobel_filt_V():
    if request.method == "POST":
        try:
            delete_images()
            image_src = 'static/uploads/img.png'
            im = Image.open(image_src).convert(mode="L")            
            sobel_mask = (
                1, 0, -1,
                2, 0, -2,
                1, 0, -1,
            )
            im_sobel = im.filter(ImageFilter.Kernel((3,3),sobel_mask,scale=4))
            im_sobel.save('static/uploads/img_sobel_V.png')
            image_url_sobel = url_for('static',filename="uploads/img_sobel_V.png")
            return jsonify({'image_url_sobel_V' : image_url_sobel})
        except Exception as e:
            print(e)