Пример #1
0
def test_swirl():
    image = img_as_float(data.checkerboard())

    swirl_params = {'radius': 80, 'rotation': 0, 'order': 2, 'mode': 'reflect'}
    swirled = tf.swirl(image, strength=10, **swirl_params)
    unswirled = tf.swirl(swirled, strength=-10, **swirl_params)

    assert np.mean(np.abs(image - unswirled)) < 0.01
Пример #2
0
def test_swirl():
    image = img_as_float(data.checkerboard())

    swirl_params = {'radius': 80, 'rotation': 0, 'order': 2, 'mode': 'reflect'}

    with expected_warnings(['Bi-quadratic.*bug']):
        swirled = tf.swirl(image, strength=10, **swirl_params)
        unswirled = tf.swirl(swirled, strength=-10, **swirl_params)

    assert np.mean(np.abs(image - unswirled)) < 0.01
Пример #3
0
 def swirl_images(self, data, strength, radius=100, center=(24, 24)):
     if data.ndim == 3:
         for i in xrange(data.shape[0]):
             img_swirled = st.swirl(data[i], center=center, strength=strength, radius=radius)
             data[i] = img_swirled
     else:
         img_swirled = st.swirl(data, center=center, strength=strength, radius=radius,
                 rotation=0, order=2)
         data = img_swirled
     return data
Пример #4
0
    def apply(self, distort_name):
        shape = self._image_array.shape

        center = np.array(self._image_array.shape)[:2] / 2
        warp_args = {'width': shape[1], 'height': shape[0]}

        if distort_name == "SWIRL":
            radius = max(shape[0], shape[1]) / 2
            result = swirl(self._image_array, center=(shape[1]/2, shape[0]/2), strength=5, 
                radius=radius, order=1, mode='nearest')
        elif distort_name == "FISH EYE LIGHT":
            warp_args['radius_func'] = lambda radius_d: self.fish_eye(0.3, radius_d)
            warp_args['zoom_factor'] = 1.6
            result = warp(self._image_array, self.radius_distort, map_args=warp_args, mode='nearest')
        elif distort_name == "FISH EYE HEAVY":
            warp_args['radius_func'] = lambda radius_d: self.fish_eye(0.6, radius_d)
            warp_args['zoom_factor'] = 2.2
            result = warp(self._image_array, self.radius_distort, map_args=warp_args, mode='nearest')
        elif distort_name == "BULGE":
            warp_args['radius_func'] = lambda radius_d: self.bulge(radius_d)
            warp_args['zoom_factor'] = 1.45
            result = warp(self._image_array, self.radius_distort, map_args=warp_args, mode='nearest')
        elif distort_name == "PINCH LIGHT":
            warp_args['radius_func'] = lambda radius_d: self.pinch(0.8, radius_d)
            warp_args['zoom_factor'] = 1
            result = warp(self._image_array, self.radius_distort, map_args=warp_args, mode='nearest')
        elif distort_name == "PINCH HEAVY":
            warp_args['radius_func'] = lambda radius_d: self.pinch(0.5, radius_d)
            warp_args['zoom_factor'] = 1
            result = warp(self._image_array, self.radius_distort, map_args=warp_args, mode='nearest')
        else:
            result = self._image_array

        return img_as_ubyte(result)
Пример #5
0
    def __getitem__(self, idx):

        global WARP_PROB, IMAGE_SIZE

        file_path = self.path + self.files[idx]
        img = cv2.imread(file_path)
    
        # Resize image to reduce computation complexity
        img = scipy.misc.imresize(img, (IMAGE_SIZE[0],IMAGE_SIZE[1],3))
        warped = swirl(img,rotation=0, strength=random.uniform(0.6,1.5), radius=random.randint(300,600),  mode = "constant")        
        
        img = np.rollaxis(img,2,0)
        img = img.astype(float)

        warped = np.rollaxis(warped, 2, 0)
        warped = warped.astype(float)
               
        # Image normalisation
        img = img/255
        
        warp_prob = random.uniform(0,1)
        if(warp_prob < WARP_PROB):
            return warped, img
        else:
            return img, img
Пример #6
0
	def swirl(self):
		'''
		implements skimage's swirl function
		'''
		self.img = transform.swirl(self.img, rotation=0, strength=10, radius=1000, order=2)

		self.refreshimg()
Пример #7
0
def batch_unswirl(images):
    from skimage.transform import swirl
    images = np.array(images)
    r = images.shape[1] * relative_swirl_radius
    # from joblib import Parallel, delayed
    # return np.array(Parallel(n_jobs=4)(delayed(swirl)(i, radius=r, **unswirl_args) for i in images))
    return np.array([swirl(i, radius=r, **unswirl_args) for i in images])
Пример #8
0
def lokal_swirl(img_in, hi, wi, chan, n_swirls, radius, strength, positioning="random", directions="random", corr_size=3):
    img = img_in.copy()
    if not positioning in  ["random", "center"]:
        raise NotImplementedError("TODO!")
    size = corr_size
    for i in range(n_swirls):
        sign = None
        if directions == "random":
            sign = np.sign(np.random.rand(1) - 0.5)[0]
        elif directions == "left":
            sign = -1
        else:
            sign = 1
        xpos, ypos = None, None
        if positioning == "random":
            xpos = random.randint(0, hi - radius)
            ypos = random.randint(0, wi - radius)
        elif positioning == "center":
            xpos = hi // 2
            ypos = wi // 2
        center = (xpos,ypos)
        img = swirl(img, rotation=0, strength=sign*strength, radius=radius, center=center)
        img[0:size] = img_in[0:size]
        img[-(size+1):] = img_in[-(size+1):]
        img[:,0:size] = img_in[:,0:size]
        img[:,-(size+1):] = img_in[:,-(size+1):]
    return img
Пример #9
0
def img_manipulation(img, mode=0):
    # img = np.array(img, dtype='int8')
    # add manipulation
    if mode == 0:  # gaussian噪声
        return util.random_noise(img, mode='gaussian', mean=0.5, var=0.3)
    elif mode == 1:  # salt噪声
        return util.random_noise(img, mode='salt')
    elif mode == 2:  # 直方图均衡化
        img = np.transpose(img, axes=[2, 0, 1])
        img1 = exposure.equalize_hist(img[0])
        img2 = exposure.equalize_hist(img[1])
        img3 = exposure.equalize_hist(img[2])
        img = np.stack([img1, img2, img3], axis=0)
        return np.transpose(img, [1, 2, 0])
    elif mode == 3:  # 改变对比度
        return exposure.rescale_intensity(1 - filters.sobel(img))
    elif mode == 4:  # 改变伽马值
        adjusted_gamma_image = exposure.adjust_gamma(img, gamma=0.4, gain=0.9)
        return adjusted_gamma_image
    elif mode == 5:  # 扭曲
        img = transform.swirl(img,
                              center=[100, 100],
                              rotation=0.3,
                              strength=10,
                              radius=120)
        return img
    elif mode == 6:  # 改变尺寸
        return transform.resize(img, (img.shape[0] * 1.5, img.shape[1] * 2))
    elif mode == 7:  # 反相
        return util.invert(img)
Пример #10
0
def tourbillion(path, force) :
    if path.endswith(".gif") :
        img = Image.open(path)
        nbFrames = img.n_frames
        try :
            duration = img.info['duration']
        except :
            duration = 40

        if ":" in force :
            _min=int(force.split(":")[0])
            _max=int(force.split(":")[-1])
            f=np.linspace(_min,_max,nbFrames)
        else :
            f=[int(force) for i in range(nbFrames)]

        for frame in range(0, nbFrames) :
            img.seek(frame)
            img.save(str(frame)+".gif")

        for frame in range(0, nbFrames) :
            image = imread(str(frame)+".gif")
            taille = max(image.shape)
            image = swirl(image, rotation=0, strength=f[frame], radius=taille)
            image = 255 * image
            imsave(str(frame)+".gif", image.astype(np.uint8))

        images = []
        for frame in range(0, nbFrames) :
            im = Image.open(str(frame)+".gif")
            images.append(im)

        images[0].save('anim.gif', save_all=True, append_images=images[1:], optimize=False, duration=duration, loop=0)

        while os.path.getsize('anim.gif') > 8e+6 :
            gifsize.resize_gif('anim.gif', duration=duration)

        return nbFrames

    else :
        image = imread(path)
        taille = max(image.shape)
        image = swirl(image, rotation=0, strength=force, radius=taille)
        image = 255 * image
        imsave('img.png', image.astype(np.uint8))
        return
Пример #11
0
def get_image11():

    #noisy = denoise_tv_chambolle(io.imread(request.args.get('link')), weight=float(request.args.get('weight')), multichannel=True)
    swirled = swirl(io.imread(request.args.get('link')), rotation=0, strength=10, radius=500, order=4)
    skimage.io.imsave('test_noise.png', swirled)
    filename = 'test_noise.png'

    return send_file(filename, mimetype='image/gif')
Пример #12
0
    def swirl(self):
        filteredImage = tr.swirl(self.rawImage, (50, 50),
                                 radius=150,
                                 rotation=45)

        self.showImage(filteredImage)
        self.rawImage = filteredImage
        print("Swirl")
Пример #13
0
def test_swirl():
    image = img_as_float(data.checkerboard())

    swirl_params = {'radius': 80, 'rotation': 0, 'order': 2, 'mode': 'reflect'}

    with expected_warnings(['Bi-quadratic.*bug']):
        swirled = tf.swirl(image, strength=10, **swirl_params)
        unswirled = tf.swirl(swirled, strength=-10, **swirl_params)

    assert np.mean(np.abs(image - unswirled)) < 0.01

    swirl_params.pop('mode')

    with expected_warnings(['Bi-quadratic.*bug']):
        swirled = tf.swirl(image, strength=10, **swirl_params)
        unswirled = tf.swirl(swirled, strength=-10, **swirl_params)

    assert np.mean(np.abs(image[1:-1, 1:-1] - unswirled[1:-1, 1:-1])) < 0.01
Пример #14
0
def twist(T):
  T = T.copy()
  T = img_as_float(T)
  height = T.shape[0]
  width = T.shape[1]
  full = swirl(T, center=(height/2, width/2),
      rotation=0, strength=10, radius=max(height,width),
      mode='wrap')
  return img_as_ubyte(full)
Пример #15
0
def augmentation(dat):
    num_cases = np.shape(dat)[0]
    for i in range(num_cases):
        swirl_stength = get_random_in_range(-.4, .4)
        dat[i] = transform.swirl(dat[i], strength=swirl_stength)
        rotation_angle = get_random_in_range(-30, 30)
        dat[i] = transform.rotate(dat[i], angle=rotation_angle)
        if np.random.random() > .5:
            dat[i] = np.flipud(dat[i])
    return dat
Пример #16
0
def swirl_image(image, prop=.5):
    if prop:
        if coin_flip(prop):
            strength = np.random.uniform(0, 3)
            radius = np.random.uniform(0, 250)
        else:
            return image
    else:
        strength = 3
        radius = 250
    return swirl(image, strength=strength, radius=radius)
Пример #17
0
def swirl_image(image, strength=10):
    image = np.array(image)
    w, h = image.shape[:2]
    sw = swirl(image, rotation=0, strength=strength, radius=max(w, h))
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        sw = img_as_ubyte(sw)

    pil_img = Image.fromarray(sw)

    return pil_img
 def __call__(self, image):
     if self.level == 0: return image
     pil = ToPILImage()(image)
     swirled = transform.swirl(
         np.array(pil),
         center=(14, 14),
         strength=10.0 * self.level,
         radius=28,
         rotation=0.0,
     )
     return ToTensor()(PIL.Image.fromarray(swirled))
Пример #19
0
    def process(self, a: np.ndarray) -> np.ndarray:
        """ Based on code taken from:
        https://stackoverflow.com/questions/30448045
        """
        # Determine the location of the center of the twirl effect.
        center = [n / 2 + o for n, o in zip(a.shape[1:3], self.offset[1:3])]

        # Run the swirl filter.
        for i in range(a.shape[Z]):
            a[i] = swirl(a[i], center[::-1], self.strength, self.radius)
        return a
Пример #20
0
def swirl():    
    image = read_image_return_scikit()
    swirled = transform.swirl(image, rotation=0, strength=10, radius=500)

    fig, (ax0, ax1) = plt.subplots(nrows=1, ncols=2, figsize=(8, 3),
                                sharex=True, sharey=True)
    setGlobalVar(swirled)
    ax0.imshow(image, cmap=plt.cm.gray)
    ax0.axis('off')
    ax1.imshow(swirled, cmap=plt.cm.gray)
    ax1.axis('off')

    plt.show()
Пример #21
0
def swirled(image, map_args={}, output_shape=None, order=1, mode='constant', cval=0.0, clip=True, preserve_range=False):
    #image = imageGlobal
    swirled = swirl(image, rotation=0, strength=10, radius=120)

    fig, (ax0, ax1) = plt.subplots(nrows=1, ncols=2, figsize=(8, 3),
                                   sharex=True, sharey=True)

    ax0.imshow(image, cmap=plt.cm.gray)
    ax0.axis('off')
    ax1.imshow(swirled, cmap=plt.cm.gray)
    ax1.axis('off')

    plt.show()
Пример #22
0
 def augment_data(self, image, target):
     images = [
         image.ravel(),
     ]
     targets = [
         target,
     ]
     image_modifiers = (lambda x: rotate(x, 90), lambda x: rotate(x, 180),
                        lambda x: rotate(x, 270), lambda x: rotate(x, 45),
                        lambda x: swirl(x))
     for i in xrange(self.augmentation):
         img = image_modifiers[i](image)
         images.append(img.ravel())
         targets.append(target)
     return images, targets
Пример #23
0
def swirled(img):
    swirled = transform.swirl(img, rotation=0, strength=20, radius=240)

    fig, (ax0, ax1) = plt.subplots(nrows=1,
                                   ncols=2,
                                   figsize=(8, 3),
                                   sharex=True,
                                   sharey=True)

    ax0.imshow(img, cmap=plt.cm.gray)
    ax0.axis('off')
    ax1.imshow(swirled, cmap=plt.cm.gray)
    ax1.axis('off')

    plt.show()
Пример #24
0
 def augment_data(self, image, target):
     images = [image.ravel(), ]
     targets = [target, ]
     image_modifiers = (
         lambda x: rotate(x, 90),
         lambda x: rotate(x, 180),
         lambda x: rotate(x, 270),
         lambda x: rotate(x, 45),
         lambda x: swirl(x)
     )
     for i in xrange(self.augmentation):
         img = image_modifiers[i](image)
         images.append(img.ravel())
         targets.append(target)
     return images, targets
Пример #25
0
 async def warp(self, ctx: commands.Context, help="", amount="0"):
     img, amount, successful = await self.getImage(ctx, "warp", help,
                                                   amount)
     if not successful:
         if (amount == 0):  #Error command
             em = discord.Embed()
             em.title = f'Error when running command'
             em.description = f"Error: {img}."
             em.color = 0xEE0000
             await ctx.send(embed=em)
             return
         else:  #Help Command
             em = discord.Embed()
             em.title = f'Usage: /warp [img|imgURL]'
             em.description = f'Randomly warps the image attached, url in the message, or the image attached before the command'
             em.add_field(
                 name="Examples",
                 value=
                 "/warp https://imgur.com/a/wUChw7w | /warp (imageAttachment)",
                 inline=False)
             em.color = 0x22BBFF
             await ctx.send(embed=em)
             return ()
     await ctx.send("Processing... (This may take a while)")
     toDelete = await self.getMessages(ctx, 1)
     # Processing
     from skimage.transform import swirl  #import works here but not at the beginning
     img = np.array(img)  #convert PIl image to Numpy
     # Swirl
     width, height = img.shape[:2]
     for x in range(5):
         img = swirl(img,
                     strength=((random.random() + 1) * -1**x),
                     radius=width / 1.4,
                     center=(random.randint(int(width / 4),
                                            int(width - width / 4)),
                             random.randint(int(height / 4),
                                            int(height - height / 4))))
         img = (img * 255).astype('uint8')
     #convert numpy array to Pillow img
     im_pil = Image.fromarray(img)
     # Convert to an attachable Discord Format
     arr = io.BytesIO()  #convert to bytes array
     im_pil.save(arr, format='PNG')
     arr.seek(0)  #seek back to beginning of file
     # Send
     await ctx.send(file=discord.File(arr, 'warp.png'))
     await ctx.channel.delete_messages(toDelete)
Пример #26
0
def swirled_with_checkerboard():
    image = data.checkerboard()
    swirled = transform.swirl(image, rotation=0, strength=10, radius=120)

    fig, (ax0, ax1) = plt.subplots(nrows=1,
                                   ncols=2,
                                   figsize=(8, 3),
                                   sharex=True,
                                   sharey=True)

    ax0.imshow(image, cmap=plt.cm.gray)
    ax0.axis('off')
    ax1.imshow(swirled, cmap=plt.cm.gray)
    ax1.axis('off')

    plt.show()
Пример #27
0
    def swirl_imgs(self, set=[], labels=[]):
        """swirls each image 3 times with a random strength between 0.5 and 2.0"""
        print('Swirling images...')
        out_set = []
        out_labels = []
        for i in range(0, len(set)):
            out_set.append(set[i])
            out_labels.append(labels[i])

            j = 0
            while j < 3:
                j += 1
                str = np.random.uniform(0.5, 2.0)
                img_swirled = swirl(set[i], strength=str)
                out_set.append(img_swirled)
                out_labels.append(labels[i])
        return np.asarray(out_set), np.asarray(out_labels)
Пример #28
0
def swirl_rotate_augmentor(dataset):
    '''
    applies random swirl, followed by random rotation
    inputs:
        1. (n x m) n samples of images, each with m features
    output:
        1. (n x m) n samples of images, each with m features, after applying the augmentation
    '''
    img_width = int(math.sqrt(dataset.shape[-1]))
    dataset = dataset.reshape(-1, img_width, img_width)
    n_samples = dataset.shape[0]
    augmented_dataset = np.zeros((n_samples, img_width, img_width))

    for i in range(n_samples):
        augmented_dataset[i] = transform.swirl(
            dataset[i, :, :],
            strength=random.uniform(-0.4, 0.4),
            rotation=random.uniform(-0.4, 0.4))

    return flatten_dataset(augmented_dataset)
Пример #29
0
 async def swirl(self, ctx: commands.Context, help="", amount="10"):
     img, amount, successful = await self.getImage(ctx, "radial", help,
                                                   amount)
     if not successful:
         if (amount == 0):  #Error command
             em = discord.Embed()
             em.title = f'Error when running command'
             em.description = f"Error: {img}."
             em.color = 0xEE0000
             await ctx.send(embed=em)
             return
         else:  #Help Command
             em = discord.Embed()
             em.title = f'Usage: /swirl [img|imgURL] [amount]'
             em.description = f'Swirls the image attached, url in the message, or the image attached before the command by [amount] from -100 to 100'
             em.add_field(
                 name="Examples",
                 value=
                 "/swirl https://imgur.com/a/wUChw7w | /swirl (imageAttachment) 30",
                 inline=False)
             em.color = 0x22BBFF
             await ctx.send(embed=em)
             return ()
     await ctx.send("Processing... (This may take a while)")
     toDelete = await self.getMessages(ctx, 1)
     # Processing
     from skimage.transform import swirl  #import works here but not at the beginning
     w, h = img.size
     img = np.array(img)  #convert PIl image to Numpy
     # Swirl
     img = swirl(img, strength=amount, radius=w / 1.3)
     img = (img * 255).astype('uint8')
     #convert numpy array to Pillow img
     im_pil = Image.fromarray(img)
     # Convert to an attachable Discord Format
     arr = io.BytesIO()  #convert to bytes array
     im_pil.save(arr, format='PNG')
     arr.seek(0)  #seek back to beginning of file
     # Send
     await ctx.send(file=discord.File(arr, 'swirl.png'))
     await ctx.channel.delete_messages(toDelete)
Пример #30
0
 def apply_filter(self,img):
     if self.filter == 0:
         return img
     elif self.filter == 1:
         img = cv2.Laplacian(img,cv2.CV_8UC3)
         return img
     elif self.filter == 2:
         img = np.array(Image.fromarray(img).filter(ImageFilter.GaussianBlur()))
         return img
     elif self.filter == 3:
         if self.sin_transform is None:
             h, w = img.shape[:2]
             flow = np.zeros((h,w,2),np.float32)
             flow[:,:,0] += np.arange(w) + np.sin(np.arange(w)/(2*np.pi*5))*10
             flow[:,:,1] += np.arange(h)[:,np.newaxis]
             self.sin_transform = flow
         res = cv2.remap(img, self.sin_transform, None, cv2.INTER_LINEAR)
         return res
     else:
         out1 = transform.swirl(img, rotation=0, strength=5, radius=200)
         return out1
Пример #31
0
    def apply_filter(self):
        self.read_image()

        if self.filter_type == 'edge':
            self.filtered_image = roberts(self.image)

        elif self.filter_type == 'red_tint':
            rgb_image = color.gray2rgb(self.image)
            red_multiplier = [1, 0, 0]
            self.filtered_image = red_multiplier * rgb_image

        elif self.filter_type == 'swirl':
            self.filtered_image = swirl(self.image,
                                        rotation=0,
                                        strength=10,
                                        radius=120)

        else:
            return None

        self.save_image()
        return self.result_file_path
Пример #32
0
def experiment2():
    import matplotlib.pyplot as plt

    from skimage import data
    from skimage.transform import swirl

    image = data.checkerboard()
    swirled = swirl(image, rotation=0, strength=0.5, radius=180)

    fig, (ax0, ax1) = plt.subplots(nrows=1,
                                   ncols=2,
                                   figsize=(8, 3),
                                   sharex=True,
                                   sharey=True,
                                   subplot_kw={'adjustable': 'box-forced'})

    ax0.imshow(image, cmap=plt.cm.gray, interpolation='none')
    ax0.axis('off')
    ax1.imshow(swirled, cmap=plt.cm.gray, interpolation='none')
    ax1.axis('off')

    plt.show()
    def random_transform(self, image):

        rotated = tf.rotate(image, self.angle)

        if random.random() < 0.5:
            rotated = horizontal_flip(rotated)
        if random.random() < 0.2:  # 20%
            rotated = vertical_flip(rotated)

        # Create Afine transform
        afine_tf = tf.AffineTransform(scale=self.scale,
                                      shear=self.shear,
                                      translation=self.translate)
        # Apply transform to image data
        modified = tf.warp(rotated, afine_tf)

        if random.random() < 0.1:  # 20%
            modified = tf.swirl(modified,
                                rotation=0,
                                strength=self.swirl,
                                radius=image.shape[1] / 2)

        return tf.resize(modified, [self.reW, self.reH])
def swirl_(im, strength, radius):
    return np.array([swirl(im_slice, rotation=0, strength=strength, radius=radius) for im_slice in im], dtype='float32')
Пример #35
0
    def buttonSave(arg):

        copy = arg[1]
        imageTemp = arg[2]
        filterTry = filterVar.get()
        if (filterTry == 1):
            copy = cv2.GaussianBlur(copy, (5, 5), 0)
        elif (filterTry == 2):
            copy = cv2.Canny(copy, 100, 150)
        elif (filterTry == 3):
            copy = filters.roberts(imageTemp)
        elif (filterTry == 4):
            copy = filters.sato(imageTemp)
        elif (filterTry == 5):
            copy = filters.scharr(imageTemp)
        elif (filterTry == 6):
            copy = filters.sobel(imageTemp)
        elif (filterTry == 7):
            copy = filters.unsharp_mask(copy, radius=30, amount=3)
        elif (filterTry == 8):
            #copy = filters.median(imageTemp, disk(5))
            b, g, r = cv2.split(copy)
            b = filters.median(b, disk(5))
            g = filters.median(g, disk(5))
            r = filters.median(r, disk(5))
            copy = cv2.merge((b, g, r))
        elif (filterTry == 9):
            copy = filters.prewitt(imageTemp)
        elif (filterTry == 10):
            copy = filters.rank.modal(imageTemp, disk(5))
        flag = 0
        if (np.ndim(copy) == 2):
            flag = 0
        else:
            flag = 1

        if (hEsitleme.get() or hGrafik.get()):
            if (flag):
                copy = cv2.cvtColor(copy, cv2.COLOR_BGR2GRAY)
            if (hGrafik.get()):
                plt.hist(copy.ravel(), 256, [0, 256])
                plt.show()
            if (hEsitleme.get()):
                copy = cv2.equalizeHist(copy)

        if (uzaysalVars[0].get()):
            reScaleRatio = float(uzaysalVarsInputs[0].get())
            if (np.ndim(copy) == 3):
                b, g, r = cv2.split(copy)
                b = transform.rescale(b, reScaleRatio)
                g = transform.rescale(g, reScaleRatio)
                r = transform.rescale(r, reScaleRatio)
                copy = cv2.merge((b, g, r))
            else:
                copy = transform.rescale(copy, reScaleRatio)

        if (uzaysalVars[1].get()):
            resizeY = float(uzaysalVarsInputs[1].get())
            resizeX = float(uzaysalVarsInputs[2].get())
            if (np.ndim(copy) == 3):
                b, g, r = cv2.split(copy)
                b = transform.resize(
                    b, (b.shape[0] // resizeX, b.shape[1] // resizeY),
                    anti_aliasing=True)
                g = transform.resize(
                    g, (g.shape[0] // resizeX, g.shape[1] // resizeY),
                    anti_aliasing=True)
                r = transform.resize(
                    r, (r.shape[0] // resizeX, r.shape[1] // resizeY),
                    anti_aliasing=True)
                copy = cv2.merge((b, g, r))
            else:
                copy = transform.resize(
                    copy, (copy.shape[0] // resizeX, copy.shape[1] // resizeY),
                    anti_aliasing=True)
        if (uzaysalVars[2].get()):
            copy = transform.swirl(copy, rotation=0, strength=10, radius=120)
        if (uzaysalVars[3].get()):
            copy = transform.rotate(copy,
                                    int(uzaysalVarsInputs[3].get()),
                                    resize=True)
        if (uzaysalVars[4].get()):
            copy = copy[:, ::-1]

        if (yogunlukVars[0].get() or yogunlukVars[1].get()):
            if (yogunlukVars[0].get()):
                startINX = int(yogunlukVars[2].get())
                finishINX = int(yogunlukVars[3].get())
                copy = exposure.rescale_intensity(copy,
                                                  in_range=(startINX,
                                                            finishINX))
            if (yogunlukVars[1].get()):
                startOUTX = int(yogunlukVars[4].get())
                finishOUTX = int(yogunlukVars[5].get())
                copy = exposure.rescale_intensity(copy,
                                                  out_range=(startOUTX,
                                                             finishOUTX))

        morfoTry = morfVar.get()
        morfoGirisN = 0
        if (np.ndim(copy) == 3):
            morfoGirisN = 1

        if (morfoTry == 1):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.area_closing(b, 128, 9)
                g = morphology.area_closing(g, 128, 9)
                r = morphology.area_closing(r, 128, 9)
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.area_closing(copy)
        elif (morfoTry == 2):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.area_opening(b, 128, 9)
                g = morphology.area_opening(g, 128, 9)
                r = morphology.area_opening(r, 128, 9)
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.area_opening(copy)
        elif (morfoTry == 3):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.erosion(b, disk(6))
                g = morphology.erosion(g, disk(6))
                r = morphology.erosion(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.erosion(copy, disk(6))
        elif (morfoTry == 4):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.dilation(b, disk(6))
                g = morphology.dilation(g, disk(6))
                r = morphology.dilation(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.dilation(copy, disk(6))
        elif (morfoTry == 5):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.opening(b, disk(6))
                g = morphology.opening(g, disk(6))
                r = morphology.opening(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.opening(copy, disk(6))
        elif (morfoTry == 6):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.closing(b, disk(6))
                g = morphology.opening(g, disk(6))
                r = morphology.opening(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.opening(copy, disk(6))
        elif (morfoTry == 7):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.white_tophat(b, disk(6))
                g = morphology.white_tophat(g, disk(6))
                r = morphology.white_tophat(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.white_tophat(copy, disk(6))
        elif (morfoTry == 8):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.black_tophat(b, disk(6))
                g = morphology.black_tophat(g, disk(6))
                r = morphology.black_tophat(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.black_tophat(copy, disk(6))
        elif (morfoTry == 10):
            if (morfoGirisN):
                copy = cv2.cvtColor(copy, cv2.COLOR_BGR2GRAY)

            copy = exposure.rescale_intensity(copy)
            local_maxima = extrema.local_maxima(copy)
            label_maxima = measure.label(local_maxima)
            copy = color.label2rgb(label_maxima,
                                   copy,
                                   alpha=0.7,
                                   bg_label=0,
                                   bg_color=None,
                                   colors=[(1, 0, 0)])
        elif (morfoTry == 9):
            if (morfoGirisN):
                copy = cv2.cvtColor(copy, cv2.COLOR_BGR2GRAY)
            copy = exposure.rescale_intensity(copy)
            h = 0.05
            h_maxima = extrema.h_maxima(copy, h)
            label_h_maxima = measure.label(h_maxima)
            copy = color.label2rgb(label_h_maxima,
                                   copy,
                                   alpha=0.7,
                                   bg_label=0,
                                   bg_color=None,
                                   colors=[(1, 0, 0)])
        arg[1] = copy
        arg[2] = imageTemp
        cv2.imshow("org", copy)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
        """
def swirl_(im, strength, radius):
    from skimage.transform import swirl
    return [swirl(im_slice, rotation=0, strength=strength, radius=radius) for im_slice in im]
Пример #37
0
 async def fry(self, ctx: commands.Context, help="", amount="20"):
     img, amount, successful = await self.getImage(ctx, "fry", help, amount)
     if not successful:
         if (amount == 0):  #Error command
             em = discord.Embed()
             em.title = f'Error when running command'
             em.description = f"Error: {img}."
             em.color = 0xEE0000
             await ctx.send(embed=em)
             return
         else:  #Help Command
             em = discord.Embed()
             em.title = f'Usage: /fry [img|imgURL] [gamma]'
             em.description = f'Deep-fries the image attached, url in the message, or the image attached before the command. Change gamma based on how dark the image is. Default gamma value is 20, range 1-500. Saturation default 3, range: 1-50'
             em.add_field(name="Aliases", value="/deepfry", inline=False)
             em.add_field(
                 name="Examples",
                 value=
                 "/fry https://imgur.com/a/wUChw7w | /deepfry (imageAttachment)",
                 inline=False)
             em.color = 0x22BBFF
             await ctx.send(embed=em)
             return
     await ctx.send("Processing... (This may take a while)")
     toDelete = await self.getMessages(ctx, 1)
     # Processing
     img = np.array(
         img)  #convert PIL image to Numpy (CV2 works with numpy BRG arrays)
     # Convert RGB to BGR
     img = cv.cvtColor(np.array(img), cv.COLOR_RGB2BGR)
     width, height = img.shape[:2]
     #Increase brightness
     value = int(
         amount
     ) * 6  #default multiplier, change depending on dark/light images
     hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
     h, s, v = cv.split(hsv)
     lim = 255 - value
     v[v > lim] = 255
     v[v <= lim] += value
     final_hsv = cv.merge((h, s, v))
     img = cv.cvtColor(final_hsv, cv.COLOR_HSV2BGR)
     #Sharpen
     kernel = np.array(
         [[-1, -1, -1], [-1, 9, -1],
          [-1, -1, -1]])  #how to modify a pixel based on surrounding pixels
     img = cv.filter2D(img, -1, kernel)
     #Change gamma and make it crusty
     gamma = int(amount)
     table = np.array([((i / 255.0)**gamma) * 255
                       for i in np.arange(0, 256)]).astype("uint8")
     img = cv.LUT(img, table)
     #Now deform the image a bit
     from skimage.transform import swirl  #import works here but if at the beginning, breaks the code for some reason
     #swirl the image at random places
     for x in range(8):
         img = swirl(img,
                     strength=((random.random() + 1) * -1**x),
                     radius=width / 1.4,
                     center=(random.randint(int(width / 4),
                                            int(width - width / 4)),
                             random.randint(int(height / 4),
                                            int(height - height / 4))))
         img = (img * 255).astype('uint8')
     #convert CV2 Numpy array to PIL
     img = cv.cvtColor(img, cv.COLOR_BGR2RGB)  #Change CV2 BGR to RGB
     im_pil = Image.fromarray(img)  #Convert to PIL
     # Increase saturation
     from PIL import ImageEnhance
     from PIL import ImageFilter
     converter = PIL.ImageEnhance.Color(im_pil)
     im_pil = converter.enhance(0.4)
     im_pil = im_pil.filter(
         ImageFilter.EDGE_ENHANCE_MORE)  #add edge detection
     # Convert to an attachable Discord Format
     arr = io.BytesIO()  #convert to bytes array
     im_pil.save(arr, format='PNG')
     arr.seek(0)  #seek back to beginning of file
     # Send
     await ctx.send(file=discord.File(arr, 'fry.png'))
     await ctx.channel.delete_messages(toDelete)
Пример #38
0
	def do_swirl(self):
		"""
		swirl image
		"""
		swirled = swirl(self.imgarray, rotation=0, strength=10, radius=150, order=2)
		self.imgarray = swirled
Пример #39
0
    \phi = \mathtt{rotation}

    s = \mathtt{strength}

    \\theta' = \phi + s \, e^{-\\rho / r + \\theta}

where ``strength`` is a parameter for the amount of swirl, ``radius`` indicates
the swirl extent in pixels, and ``rotation`` adds a rotation angle.  The
transformation of ``radius`` into :math:`r` is to ensure that the
transformation decays to :math:`\\approx 1/1000^{\mathsf{th}}` within the
specified radius.

"""
import matplotlib.pyplot as plt

from skimage import data
from skimage.transform import swirl


image = data.checkerboard()
swirled = swirl(image, rotation=0, strength=10, radius=120, order=2)

fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(8, 3), sharex=True, sharey=True, subplot_kw={'adjustable':'box-forced'})

ax0.imshow(image, cmap=plt.cm.gray, interpolation='none')
ax0.axis('off')
ax1.imshow(swirled, cmap=plt.cm.gray, interpolation='none')
ax1.axis('off')

plt.show()
Пример #40
0
    s = \mathtt{strength}

    \\theta' = \phi + s \, e^{-\\rho / r + \\theta}

where ``strength`` is a parameter for the amount of swirl, ``radius`` indicates
the swirl extent in pixels, and ``rotation`` adds a rotation angle.  The
transformation of ``radius`` into :math:`r` is to ensure that the
transformation decays to :math:`\\approx 1/1000^{\mathsf{th}}` within the
specified radius.

"""
import matplotlib.pyplot as plt

from skimage import data
from skimage.transform import swirl


image = data.checkerboard()
swirled = swirl(image, rotation=0, strength=-5, radius=120)

fig, (ax0, ax1) = plt.subplots(nrows=1, ncols=2, figsize=(8, 3),
                               sharex=True, sharey=True,
                               subplot_kw={'adjustable':'box-forced'})

ax0.imshow(image, cmap=plt.cm.gray, interpolation='none')
ax0.axis('off')
ax1.imshow(swirled, cmap=plt.cm.gray, interpolation='none')
ax1.axis('off')

plt.show()