Пример #1
0
def augmentate(image):

    # Rotates by an angle of [1, 5]
    if (random.random() >= 0.5):
        angle = random.randint(1, 15)
        image_center = tuple(np.array(image.shape[1::-1]) / 2)
        rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)
        image = cv2.warpAffine(image,
                               rot_mat,
                               image.shape[1::-1],
                               flags=cv2.INTER_LINEAR)

    # Flips horizontally
    # if (random.random() >= 0.5):
    #     cv2.flip(image, 1, image)

    # Gaussian noise
    # if (random.random() >= 0.5):
    #     noise =  image.copy()
    #     cv2.randn(noise, (0), (150))
    #     image += noise

    # Uniform noise
    if (random.random() >= 0.5):
        noise = image.copy()
        cv2.randu(noise, (0), (1))
        image += noise

    # print(image.shape)
    # cv2.imshow('teste', image)
    # cv2.waitKey(5000)
    return image
Пример #2
0
def augment_image(rgbImg):
    augmented_images = []

    # original image
    augmented_images.append(rgbImg)

    # fliped x-axis
    rimg = rgbImg.copy()
    cv2.flip(rimg, 1, rimg)
    augmented_images.append(rimg)

    # add gaussian noise
    for _ in range(10):
        gaussian_noise = rgbImg.copy()
        cv2.randn(gaussian_noise, 0, 150)
        augmented_images.append(rgbImg + gaussian_noise)
        augmented_images.append(rimg + gaussian_noise)

    for _ in range(10):
        uniform_noise = rgbImg.copy()
        cv2.randu(uniform_noise, 0, 1)
        augmented_images.append(rgbImg + uniform_noise)
        augmented_images.append(rimg + uniform_noise)

    return augmented_images
Пример #3
0
def gen_saltandpepper_rect():
	h = random.randint(10,15)
	w = random.randint(36,43)
	rect = np.zeros((h,w))
	cv2.randu(rect,0,255)
	
	return rect
def collectNegSamples(path_of_input_images, winW, winH, featureLength, hog):
    # path_of_input_images is the path of the input images
    # featureLenght is the length of the features
    # hog is the HOGDescriptor

    no_of_windows_per_image = 10 # number of negative windows sampled from each image
    list_of_files = os.listdir(path_of_input_images)

    samples = np.zeros((len(list_of_files)*no_of_windows_per_image, featureLength), dtype=np.float32)
    counter = 0

    xIndex = np.zeros((1), dtype=np.int32)
    yIndex = np.zeros((1), dtype=np.int32)

    for names in list_of_files:
        fileName = os.path.join(path_of_input_images, names)
        for i in range(no_of_windows_per_image):
            img = cv2.imread(fileName)

            # generate a random index inside the image
            cv2.randu(xIndex, 0, img.shape[0]-winH)
            cv2.randu(yIndex, 0, img.shape[1]-winW)
            # get a window of 128x64 image

            img_H_W = img[xIndex[0]:xIndex[0]+winH, yIndex[0]:yIndex[0]+winW, :]

            # get the hog descriptor
            h = hog.compute(img_H_W)

            # append this to the samples file
            samples[counter, :] = h.reshape(-1, h.shape[0])
            counter = counter + 1
    return samples
Пример #5
0
def generate_background(size=(960, 1280),
                        nb_blobs=100,
                        min_rad_ratio=0.01,
                        max_rad_ratio=0.05,
                        min_kernel_size=50,
                        max_kernel_size=300):
    """ Generate a customized background image
    Parameters:
      size: size of the image
      nb_blobs: number of circles to draw
      min_rad_ratio: the radius of blobs is at least min_rad_size * max(size)
      max_rad_ratio: the radius of blobs is at most max_rad_size * max(size)
      min_kernel_size: minimal size of the kernel
      max_kernel_size: maximal size of the kernel
    """
    img = np.zeros(size, dtype=np.uint8)
    dim = max(size)
    cv.randu(img, 0, 255)
    cv.threshold(img, random_state.randint(256), 255, cv.THRESH_BINARY, img)
    background_color = int(np.mean(img))
    blobs = np.concatenate([
        random_state.randint(0, size[1], size=(nb_blobs, 1)),
        random_state.randint(0, size[0], size=(nb_blobs, 1))
    ],
                           axis=1)
    for i in range(nb_blobs):
        col = get_random_color(background_color)
        cv.circle(
            img, (blobs[i][0], blobs[i][1]),
            np.random.randint(int(dim * min_rad_ratio),
                              int(dim * max_rad_ratio)), col, -1)
    kernel_size = random_state.randint(min_kernel_size, max_kernel_size)
    cv.blur(img, (kernel_size, kernel_size), img)
    return img
def addNoise(img):
    currentImg = cv2.imread(img, 0)
    width, height = img.shape
    noise = np.zeros((width, height))
    cv2.randu(noise, 0, 256)
    noiseStrength = 0.4
    noisy = currentImg + np.array(noiseStrength * noise, dtype=np.int)
    cv2.imwrite('./ImagesNoisy/noise_' + img, noisy)
Пример #7
0
 def createGrayScaleRandomImage(self, size, show=False):
     img = np.ones(size, dtype=np.float64)
     cv2.randu(img, 0, 255)
     if show:
         cv2.imshow("img", img)
         cv2.waitKey(0)
         cv2.destroyAllWindows()
     return img
Пример #8
0
 def erlang_noise(self):
     self.image = self.tmp
     gamma = 1.5
     invGamma = 1.0 / gamma
     table = np.array([((i / 255.0) ** invGamma) * 255
         for i in np.arange(0, 256)]).astype("uint8")
     cv2.randu(table, 1, 1)
     self.image = cv2.LUT(self.image, table)
     self.displayImage(2)
Пример #9
0
def smoothing(img):
    # smooth_img = cv2.GaussianBlur(img, (7, 7), 0)
    gaussian_noise = img.copy()
    cv2.randn(gaussian_noise, 0, 150)
    noisy1 = (img + gaussian_noise)

    uniform_noise = img.copy()
    cv2.randu(uniform_noise, 0, 1)
    noisy = img + gaussian_noise
    return noisy, noisy1
Пример #10
0
def add_salt_and_pepper(img):
    """ Add salt and pepper noise to an image """
    noise = np.zeros((img.shape[0], img.shape[1]), dtype=np.uint8)
    cv.randu(noise, 0, 255)
    black = noise < 30
    white = noise > 225
    img[white > 0] = 255
    img[black > 0] = 0
    cv.blur(img, (5, 5), img)
    return np.empty((0, 2), dtype=np.int)
Пример #11
0
 def gurultu_ekle(self):
     resim = cv2.imread(self.resim_yolu, 0)
     height, width = resim.shape[:2]
     gurultu = np.zeros((height, width))
     cv2.randu(gurultu, 0, 256)
     noisy_gray = resim + np.array(0.6 * gurultu, dtype=np.int)
     cv2.imwrite('./gurultulu_resim.jpg', noisy_gray)
     sonuc = './gurultulu_resim.jpg'
     pixmap = QPixmap(sonuc)
     self.lbl_resim_12.setScaledContents(True)
     self.lbl_resim_12.setPixmap(pixmap)
Пример #12
0
 def apply(self, image):
     im = np.zeros(image.shape, np.uint8)
     if(len(image.shape)!=3):
         l = self.low
         u = self.up
     else:
         l = (self.low,self.low,self.low)
         u = (self.up,self.up,self.up)
     cv2.randu(im, l,u)
     image_noise = cv2.add(image, im)
     return image_noise
 def Noisy(self):
     image = cv2.imread('./images/Original_Gurultu.jpg', 0)
     height, width = image.shape[:2]
     noise = np.zeros((height, width))
     cv2.randu(noise, 0, 256)
     noisy_gray = image + np.array(0.2 * noise, dtype=np.int)
     cv2.imwrite('./images/noisy.jpg', noisy_gray)
     sonuc = './images/noisy.jpg'
     pixmap = QPixmap(sonuc)
     self.lbl_image_noisy.setScaledContents(True)
     self.lbl_image_noisy.setPixmap(pixmap)
Пример #14
0
 def createColorRandomImage(self, size, show=False):
     new_size = (size[0], size[1], 3)
     img = np.ones(new_size, dtype=np.uint8)
     bgr = cv2.split(img)
     for i in range(3):
         cv2.randu(bgr[i], 0, 255)
     img = cv2.merge(bgr)
     if show:
         cv2.imshow("img", img)
         cv2.waitKey(0)
         cv2.destroyAllWindows()
     return img
def additive_speckle_noise(img, keypoints, intensity=5):
    """ Add salt and pepper noise to an image
    Parameters:
      intensity: the higher, the more speckles there will be
    """
    noise = np.zeros(img.shape, dtype=np.uint8)
    cv.randu(noise, 0, 256)
    black = noise < intensity
    white = noise > 255 - intensity
    noisy_img = img.copy()
    noisy_img[white > 0] = 255
    noisy_img[black > 0] = 0
    return (noisy_img, keypoints)
Пример #16
0
def salt_and_peper(im, fraction=0.01):

    assert (0 < fraction <= 1.), "Fraction must be in (0, 1]"

    sp = np.zeros(im.shape)
    percent = round(fraction * 100 / 2.)

    cv2.randu(sp, 0, 100)

    # quarter salt quarter pepper
    im_sp = im.copy()
    im_sp[sp < percent] = 0
    im_sp[sp > 100 - percent] = 255
    return im_sp
Пример #17
0
def salt_and_peper(im, fraction = 0.01):

    assert (0 < fraction <= 1.), "Fraction must be in (0, 1]"

    sp = np.zeros(im.shape)
    percent = round(fraction * 100 / 2.)

    cv2.randu(sp, 0, 100)

    # quarter salt quarter pepper
    im_sp = im.copy()
    im_sp [sp < percent] = 0
    im_sp [sp > 100 - percent] = 255
    return im_sp
Пример #18
0
def dropout(i,p):
    mask = np.empty(i.shape, dtype=np.int16)
    mask = cv2.randu(mask,0,255)

    val, mask = cv2.threshold(mask,p*255,255,cv2.THRESH_BINARY)
    mask = np.asarray(mask,dtype=np.float64) / 255.0
    return cv2.multiply(i,mask)
Пример #19
0
 def do_transform(self, image, is_y):
     if self.store.apply_transform:
         for i in range(image.shape[2]):
             image[..., i] += cv2.randu(
                 np.zeros(image.shape[:-1], dtype=np.int16), (0),
                 (self.store.strength)).astype(np.uint8)
     return image
Пример #20
0
def addSaltAndPepper(input):
    img = cv2.imread(str(input), cv2.IMREAD_COLOR)
    noise = np.zeros((img.shape[0], img.shape[1]), img.dtype)
    cv2.randu(noise, 0, 255)
    salt = noise > 250
    pepper = noise < 5
    img2 = img.copy()
    img2[salt == True] = 255
    img2[pepper == True] = 0
    plt.subplot("121")
    plt.title("IMG 1")
    plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    plt.subplot("122")
    plt.title("IMG 2")
    plt.imshow(cv2.cvtColor(img2, cv2.COLOR_BGR2RGB))
    plt.show()
Пример #21
0
def main():
    print(help_message)

    w, h = 512, 512

    args, _args_list = getopt.getopt(sys.argv[1:], 'o:', [])
    args = dict(args)
    out = None
    if '-o' in args:
        fn = args['-o']
        out = cv.VideoWriter(args['-o'], cv.VideoWriter_fourcc(*'DIB '), 30.0,
                             (w, h), False)
        print('writing %s ...' % fn)

    a = np.zeros((h, w), np.float32)
    cv.randu(a, np.array([0]), np.array([1]))

    def process_scale(a_lods, lod):
        d = a_lods[lod] - cv.pyrUp(a_lods[lod + 1])
        for _i in xrange(lod):
            d = cv.pyrUp(d)
        v = cv.GaussianBlur(d * d, (3, 3), 0)
        return np.sign(d), v

    scale_num = 6
    for frame_i in count():
        a_lods = [a]
        for i in xrange(scale_num):
            a_lods.append(cv.pyrDown(a_lods[-1]))
        ms, vs = [], []
        for i in xrange(1, scale_num):
            m, v = process_scale(a_lods, i)
            ms.append(m)
            vs.append(v)
        mi = np.argmin(vs, 0)
        a += np.choose(mi, ms) * 0.025
        a = (a - a.min()) / a.ptp()

        if out:
            out.write(a)
        vis = a.copy()
        draw_str(vis, (20, 20), 'frame %d' % frame_i)
        cv.imshow('a', vis)
        if cv.waitKey(5) == 27:
            break

    print('Done')
Пример #22
0
def main():
    print(help_message)

    w, h = 512, 512

    args, args_list = getopt.getopt(sys.argv[1:], 'o:', [])
    args = dict(args)
    out = None
    if '-o' in args:
        fn = args['-o']
        out = cv.VideoWriter(args['-o'], cv.VideoWriter_fourcc(*'DIB '), 30.0, (w, h), False)
        print('writing %s ...' % fn)

    a = np.zeros((h, w), np.float32)
    cv.randu(a, np.array([0]), np.array([1]))

    def process_scale(a_lods, lod):
        d = a_lods[lod] - cv.pyrUp(a_lods[lod+1])
        for _i in xrange(lod):
            d = cv.pyrUp(d)
        v = cv.GaussianBlur(d*d, (3, 3), 0)
        return np.sign(d), v

    scale_num = 6
    for frame_i in count():
        a_lods = [a]
        for i in xrange(scale_num):
            a_lods.append(cv.pyrDown(a_lods[-1]))
        ms, vs = [], []
        for i in xrange(1, scale_num):
            m, v = process_scale(a_lods, i)
            ms.append(m)
            vs.append(v)
        mi = np.argmin(vs, 0)
        a += np.choose(mi, ms) * 0.025
        a = (a-a.min()) / a.ptp()

        if out:
            out.write(a)
        vis = a.copy()
        draw_str(vis, (20, 20), 'frame %d' % frame_i)
        cv.imshow('a', vis)
        if cv.waitKey(5) == 27:
            break

    print('Done')
def noisy(noise_typ,image):
   if noise_typ == "gauss":
       gaussian_noise = np.zeros((image.shape[0], image.shape[1]), dtype=np.uint8)
       cv2.randn(gaussian_noise, 128, 20)

       gaussian_noise = (gaussian_noise * 0.5).astype(np.uint8)
       noisy_image = cv2.add(image, gaussian_noise)
       read_save_image(noisy_image)

   elif noise_typ == "s&p":
       uniform_noise = np.zeros((image.shape[0], image.shape[1]), dtype=np.uint8)
       cv2.randu(uniform_noise, 0, 255)
       impulse_noise = uniform_noise.copy()

       ret, impulse_noise = cv2.threshold(impulse_noise, 250, 255, cv2.THRESH_BINARY)
       noisy_image = cv2.add(image, impulse_noise)
       read_save_image(noisy_image)
Пример #24
0
def augment_data(x, y):
    augmented_data = []
    augmented_labels = []
    for i in range(0, len(x)):
        im = x[i]
        lab = y[i]
        for img in (im, lab):
            shape = img.shape
            rows = shape[0]
            cols = shape[1]
            transforms = []
            #Add flips
            transforms.append(img)
            transforms.append(cv2.flip(img, 0))
            transforms.append(cv2.flip(img, 1))
            #Add rotations
            m1 = cv2.getRotationMatrix2D((cols / 2, rows / 2), 90, 1)
            m2 = cv2.getRotationMatrix2D((cols / 2, rows / 2), 180, 1)
            m3 = cv2.getRotationMatrix2D((cols / 2, rows / 2), 270, 1)
            transforms.append(cv2.warpAffine(img, m1, (rows, cols)))
            transforms.append(cv2.warpAffine(img, m2, (rows, cols)))
            transforms.append(cv2.warpAffine(img, m3, (rows, cols)))
            #Add translations
            dist_r = int(rows / 10)
            dist_c = int(cols / 10)
            t1 = np.float32([[1, 0, dist_r], [0, 1, dist_c]])
            t2 = np.float32([[1, 0, -dist_r], [0, 1, dist_c]])
            t3 = np.float32([[1, 0, dist_r], [0, 1, -dist_c]])
            t4 = np.float32([[1, 0, -dist_r], [0, 1, -dist_c]])
            transforms.append(cv2.warpAffine(img, t1, (rows, cols)))
            transforms.append(cv2.warpAffine(img, t2, (rows, cols)))
            transforms.append(cv2.warpAffine(img, t3, (rows, cols)))
            transforms.append(cv2.warpAffine(img, t4, (rows, cols)))
            #Add scaling
            scout1 = cv2.resize(img, None, fx=1.5, fy=1.5)
            scout2 = cv2.resize(img, None, fx=2, fy=2)
            transforms.append(scout1[int(rows / 4):int(5 * rows / 4),
                                     int(cols / 4):int(5 * cols / 4)])
            transforms.append(scout2[int(rows / 2):int(3 * rows / 2),
                                     int(cols / 2):int(3 * cols / 2)])
            if img.shape[2] is 3:
                #Add gaussian and salt and pepper noise
                noise1 = cv2.randn(np.zeros(img.shape), 0, 0.05)
                noise2 = cv2.randn(np.zeros(img.shape), 0, 0.1)
                spnoise = cv2.randu(np.zeros(img.shape), 0, 255)
                noise3 = img.copy()
                noise3[spnoise > 225] = 255
                noise3[spnoise < 30] = 0
                transforms.append(img + noise1)
                transforms.append(img + noise2)
                transforms.append(noise3)
                augmented_data.extend(transforms)
            else:
                transforms.append(img)
                transforms.append(img)
                transforms.append(img)
                augmented_labels.extend(transforms)
    return augmented_data, augmented_labels
def main():
    # read an image
    img = cv2.imread('../figures/flower.png')
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # initialize noise image with zeros
    noise = np.zeros((400, 600))

    # fill the image with random numbers in given range
    cv2.randu(noise, 0, 255)

    noisy_gray = gray + np.array(0.2 * noise, dtype=np.int)

    kernel = np.ones((5, 5), np.float32) / 25
    dst = cv2.filter2D(gray, -1, kernel)

    # Do plot
    plot_cv_img(gray, dst)
    def generate_random(self, random_range, size=(1, )):
        """
           random number generator
        """
        mean = random_range['mean']
        spread = random_range['spread'] * self.discount_coeff
        result = np.zeros(size)
        if random_range['method'] == 'uniform':
            cv2.randu(result, mean - spread, mean + spread)
        elif random_range['method'] == 'normal':
            cv2.randn(result, mean=mean, stddev=spread)
        else:
            raise ValueError("Wrong sampling method")
        result = np.exp(result) if random_range['exp'] else result

        if size == (1, ):
            result = result[0]
        return result
Пример #27
0
def crop_rect(big_image, x, y, width, height):
    # Crops the rectangle from the big image and returns a cropped image
    # Special care is taken to avoid cropping beyond the edge of the image.
    # It fills this area in with random pixels

    (big_height, big_width, channels) = big_image.shape
    if x >= 0 and y >= 0 and (y + height) < big_height and (x +
                                                            width) < big_width:
        crop_img = img[y:y + height, x:x + width]
    else:
        #print "Performing partial crop"
        #print "x: %d  y: %d  width: %d  height: %d" % (x,y,width,height)
        #print "big_width: %d  big_height: %d" % (big_width, big_height)
        crop_img = np.zeros((height, width, 3), np.uint8)
        cv2.randu(crop_img, (0, 0, 0), (255, 255, 255))

        offset_x = 0
        offset_y = 0
        if x < 0:
            offset_x = -1 * x
            x = 0
            width -= offset_x
        if y < 0:
            offset_y = -1 * y
            y = 0
            height -= offset_y
        if (x + width) >= big_width:
            offset_x = 0
            width = big_width - x
        if (y + height) >= big_height:
            offset_y = 0
            height = big_height - y

        #print "offset_x: %d  offset_y: %d, width: %d, height: %d" % (offset_x, offset_y, width, height)

        original_crop = img[y:y + height - 1, x:x + width - 1]
        (small_image_height, small_image_width, channels) = original_crop.shape
        #print "Small shape: %dx%d" % (small_image_width, small_image_height)
        # Draw the small image onto the large image
        crop_img[offset_y:offset_y + small_image_height,
                 offset_x:offset_x + small_image_width] = original_crop

    #cv2.imshow("Test", crop_img)
    return crop_img
Пример #28
0
def noise(cnt):  #노이즈
    x_batch = []

    im = np.zeros((52, 52), np.uint8)
    noise = cv2.randu(im, (0), (10))

    for i in range(cnt, cnt + batch_size):
        x_batch.append(np.reshape((images[i] + noise), (2704, )) / 255)

    return x_batch
Пример #29
0
def crop_rect(big_image, x,y,width,height):
    # Crops the rectangle from the big image and returns a cropped image
    # Special care is taken to avoid cropping beyond the edge of the image.
    # It fills this area in with random pixels

    (big_height, big_width, channels) = big_image.shape
    if x >= 0 and y >= 0 and (y+height) < big_height and (x+width) < big_width:
        crop_img = img[y:y+height, x:x+width]
    else:
        #print "Performing partial crop"
        #print "x: %d  y: %d  width: %d  height: %d" % (x,y,width,height)
        #print "big_width: %d  big_height: %d" % (big_width, big_height)
        crop_img = np.zeros((height, width, 3), np.uint8)
        cv2.randu(crop_img, (0,0,0), (255,255,255))

        offset_x = 0
        offset_y = 0
        if x < 0:
            offset_x = -1 * x
            x = 0
            width -= offset_x
        if y < 0:
            offset_y = -1 * y
            y = 0
            height -= offset_y
        if (x+width) >= big_width:
            offset_x = 0
            width = big_width - x
        if (y+height) >= big_height:
            offset_y = 0
            height = big_height - y

        #print "offset_x: %d  offset_y: %d, width: %d, height: %d" % (offset_x, offset_y, width, height)

        original_crop =  img[y:y+height-1, x:x+width-1]
        (small_image_height, small_image_width, channels) = original_crop.shape
        #print "Small shape: %dx%d" % (small_image_width, small_image_height)
        # Draw the small image onto the large image
        crop_img[offset_y:offset_y+small_image_height, offset_x:offset_x+small_image_width] = original_crop


    #cv2.imshow("Test", crop_img)
    return crop_img
Пример #30
0
def salt_pepper(image, prob=0.01):
    uniform_noise = np.zeros((image.shape[0], image.shape[1]), dtype=np.uint8)

    cv.randu(uniform_noise, 0, 255)
    ret, impulse_noise1 = cv.threshold(uniform_noise, 255 - prob * 255, 255, cv.THRESH_BINARY)
    impulse_noise1 = (impulse_noise1).astype(np.uint8)

    cv.randu(uniform_noise, 0, 255)
    ret, impulse_noise2 = cv.threshold(uniform_noise, 255 - prob * 255, 255, cv.THRESH_BINARY)
    impulse_noise2 = (impulse_noise2).astype(np.uint8)

    if np.ndim(image) > 2:
        impulse_noise1 = np.dstack([impulse_noise1] * 3)
        impulse_noise2 = np.dstack([impulse_noise2] * 3)

    dumb = cv.add(image, impulse_noise1)
    dumb = cv.subtract(dumb, impulse_noise2)

    return dumb
Пример #31
0
 def noise(self, stddev, nt, mean=0, y_start=0, y_end=0):
     if y_end <= 0:
         y_end = self.iheight
     arr = self.img_cv2.copy()
     noisy_img = arr.copy()
     if nt == AUG_NOISE_GAU:
         cv2.randn(arr, mean, stddev)
     elif nt == AUG_NOISE_UNI:
         cv2.randu(arr, mean, stddev)
     else:
         raise Exception("Invalid noise type specified")
     if y_start == 0 and (y_end >= (self.iheight - 1) or y_end == 0):
         noisy_img = np.add(self.img_cv2, arr)
     else:
         yi = y_start
         while yi < y_end and yi < self.iheigh:
             noisy_img[yi, :, :] = np.add(self.img_cv2[yi, :, :],
                                          arr[yi, :, :])
             yi += 1
     return np.clip(noisy_img, 0.0, 255.0)
Пример #32
0
def add_salt_pepper_and_pass_median_filter():
    img = cv2.imread("../../img/Lenna.png", cv2.IMREAD_GRAYSCALE)

    noise = np.zeros(img.shape, np.uint8)
    img2 = np.zeros(img.shape, np.uint8)
    img3 = np.zeros(img.shape, np.uint8)
    salt = np.zeros(img.shape, np.uint8)
    pepper = np.zeros(img.shape, np.uint8)

    # Kernel size
    ksize = 0
    # Amount of noise:
    #   means that values less than 'amount' are set to 0 and values higher than (255 - amount) are set to 255
    amount = 5

    cv2.namedWindow("img3", cv2.WINDOW_KEEPRATIO);
    cv2.namedWindow("img2", cv2.WINDOW_KEEPRATIO);
    cv2.createTrackbar("ksize", "img3", ksize, 15, doNothing)
    cv2.createTrackbar("amount", "img2", amount, 120, doNothing)

    cv2.randu(noise, 0, 255)

    while cv2.waitKey(1) != ord('q'):
        amount = cv2.getTrackbarPos("amount", "img2")
        ksize = cv2.getTrackbarPos("ksize", "img3")

        img2 = np.copy(img)

        salt = noise > 255 - amount
        pepper = noise < amount

        img2[salt == True] = 255
        img2[pepper == True] = 0

        img3 = cv2.medianBlur(img2, (ksize + 1) * 2 - 1)

        cv2.imshow("img", img)
        cv2.imshow("img2", img2)
        cv2.imshow("img3", img3)

    cv2.destroyAllWindows()
def gaussian_noise(img, mean=0, std=0.1):
    ''' Adding gaussian noise to the image
    Args
        img : MRI image
        mean : pixel mean of image
        std : pixel standard deviation of image
    Returns
        gaussain_img : blurred MRI image
    '''
    # convert image to 1-channel
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    w, h = img.shape
    noise = np.zeros((w, h))  # initialize a noise filter.

    cv2.randu(noise, mean, 256)  # set the noise filter with gaussian distr.

    gaus_img = img + np.array(std * noise, dtype=np.uint8)
    gaus_img = cv2.cvtColor(gaus_img, cv2.COLOR_GRAY2BGR)

    return gaus_img
Пример #34
0
 def tick(self):
     self.i += 1
     board = self.board
     buff1 = self.buff_bordered1
     buff2 = self.buff_bordered2
     buff2_in_roi = self.buff2_in_roi
     cv2.copyMakeBorder(
         board, 1, 1, 1, 1, dst=buff1, borderType=cv2.BORDER_WRAP
     )
     cv2.filter2D(buff1, -1, morph_kernel, dst=buff2)
     cv2.threshold(buff2, 3, 0, cv2.THRESH_TOZERO_INV, dst=buff2)
     cv2.scaleAdd(buff2_in_roi, 1, board, dst=board)
     cv2.threshold(board, 2, 1, cv2.THRESH_BINARY, dst=board)
     if self.i >= self.noise_interval > 0:
         self.i = 0
         cv2.randu(self.noise_indices, 0, self.n_pixels)
         self.noise[:] = 0
         self.noise.ravel()[self.noise_indices] = 1
         cv2.bitwise_or(
             cv2.UMat(self.noise), board, dst=board
         )
     return board
Пример #35
0
def augment(img, opp):
    if opp is None or opp == '':
        return img # no change.
    subopps = opp.split(' ')
    if 'mirror' in subopps:
        img = cv2.flip(img, flipCode=1)
    if 'brighten' in subopps or 'darken' in subopps:
        global brighten
        if brighten is None:
            brighten = np.zeros(shape=img.shape, dtype=np.uint8)
        if len(img.shape) == 3:
            brighten[:,:,2] = 80
        else:
            brighten[:,:] = 80
        if len(img.shape) == 3:
            hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
            if 'brighten' in subopps:
                hsv = cv2.add(hsv, brighten)
            else: # darken
                hsv = cv2.subtract(hsv, brighten)
            img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
        else: # gray-scale
            if 'brighten' in subopps:
                img = cv2.add(img, brighten)
            else: # darken
                img = cv2.subtract(img, brighten)
    if 'equalize_hist' in subopps:
        if len(img.shape) == 3:
            y, cr, cb = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2YCR_CB))
            y = cv2.equalizeHist(y)
            img = cv2.cvtColor(cv2.merge((y, cr, cb)), cv2.COLOR_YCR_CB2BGR)
        else:
            img = cv2.equalizeHist(img)
    blur_opps = [opp for opp in subopps if 'blur' in opp]
    if len(blur_opps) > 0:
        blur = blur_opps[0]
        amount = 15
        if len(blur.split('_')) > 1:
            amount = int(blur.split('_')[1])
        assert amount % 2 == 1
        img = cv2.GaussianBlur(img,(amount,amount),0)
    if 'shift_' in opp:
        pass # crop a slightly smaller region out of the image flush with one of the sides.
        # percentage of image width. 0.9 and shift
        width = img.shape[0] # should be same as height
        new_width = int(width*0.95)
        gap = width-new_width
        start_px = gap/2
        if '_up' in opp:
            img = img[0:new_width,start_px:start_px+new_width]
        elif '_down' in opp:
            img = img[gap:,start_px:start_px+new_width]
        elif '_left' in opp:
            img = img[start_px:start_px+new_width,0:new_width]
        elif '_right' in opp:
            img = img[start_px:start_px+new_width,gap:]
        img = cv2.resize(img, (width, width))
    if 'noise' in opp:
        global random_noise
        if random_noise is None:
            random_noise = np.zeros(shape=img.shape, dtype=np.uint8)
            cv2.randu(random_noise, 0, 256)
            random_noise = cv2.GaussianBlur(random_noise,(5,5),0)
        img = cv2.addWeighted(img,0.90,random_noise,0.10,0)
    if 'glasses' in opp: # Periocular-specific
        pass # TODO TODO
    return img
Пример #36
0
if __name__ == "__main__":
    print help_message

    w, h = 512, 512

    args, args_list = getopt.getopt(sys.argv[1:], "o:", [])
    args = dict(args)
    out = None
    if "-o" in args:
        fn = args["-o"]
        out = cv2.VideoWriter(args["-o"], cv.CV_FOURCC(*"DIB "), 30.0, (w, h), False)
        print "writing %s ..." % fn

    a = np.zeros((h, w), np.float32)
    cv2.randu(a, np.array([0]), np.array([1]))

    def process_scale(a_lods, lod):
        d = a_lods[lod] - cv2.pyrUp(a_lods[lod + 1])
        for i in xrange(lod):
            d = cv2.pyrUp(d)
        v = cv2.GaussianBlur(d * d, (3, 3), 0)
        return np.sign(d), v

    scale_num = 6
    for frame_i in count():
        a_lods = [a]
        for i in xrange(scale_num):
            a_lods.append(cv2.pyrDown(a_lods[-1]))
        ms, vs = [], []
        for i in xrange(1, scale_num):