Beispiel #1
0
def graficos():
    '''
    Con esta funcion, importamos graficos agrupados por generaciones y los imprimimos.
    '''
    from PIL import Image
    data = opc.cleaning('input/pokemon.csv')
    print(
        f'Por si te interesa, los datos estadisticos agrupados por generaciones son: '
    )
    total_gen = data.groupby("Generation").agg({
        "Attack": "mean",
        "Defense": "mean",
    }).plot.line()
    plt.title('Media de ataque y defensa por generacion')
    plt.savefig("output/Meanattack.jpg", bbox_inches='tight')
    max_gen = data.groupby("Generation").agg({
        "Attack": "max",
        "Defense": "max",
    }).plot.bar()
    plt.title('Ataques y defensas mas altos de cada generación')
    plt.savefig("output/Maxattack.jpg", bbox_inches='tight')
    min_gen = data.groupby("Generation").agg({
        "Attack": "min",
        "Defense": "min",
    }).plot.barh()
    plt.title('Ataques y defensas mas bajos de cada generacion')
    plt.savefig("output/Minattack.jpg", bbox_inches='tight')
    img = Image.open('output/Meanattack.jpg')
    img.show()
    img2 = Image.open('output/Minattack.jpg')
    img2.show()
    img3 = Image.open('output/Maxattack.jpg')
    img3.show()
Beispiel #2
0
  def __getitem__(self, idx):
    """
    returns image data & target for the corresponding index
    """
    try:
      bg_image = Image.open(self.bg_images[idx]).convert('L') # BG Images
      
      bgfg_image = Image.open(self.bgfg_images[idx]).convert('L') # BG_FG Images  
      
      mask_image = Image.open(self.mask_images[idx]).convert('L') # Mask Images

      depth_map = Image.open(self.depth_maps[idx]).convert('L') # Depth Images

      ## Transformed Images
      bg_image = self.bg_transforms(bg_image)
      bgfg_image = self.bgfg_transforms(bgfg_image)
      mask_image = self.mask_transforms(mask_image) # first transform the image
      depth_map = self.depthmap_transforms(depth_map)

      # upd_mask = mask_image.unsqueeze(0) # then add one channel by unsqueezing it
      # print('shape of mask_image', upd_mask.size())

      return {"bg": bg_image, "bgfg": bgfg_image, "mask": mask_image, "dpmap": depth_map} # dict way of returning Depth Map
      # also add "bg": bg_image,
    

    except Exception as e:
      print("Image {0} skipped due to {1}".format(self.bgfg_images[idx],e)) # this is only if some images can't be identified by PIL
Beispiel #3
0
def display_image(url):
  """Downloads an image from a URL and displays it in Databricks."""
  filename = url.split('/')[-1]
  filepath = os.path.join(model_dir, filename)
  urllib.request.urlretrieve(url, filepath)
  image = os.path.join(model_dir, filename)
  image_png = image.replace('.jpg','.png')
  Image.open(image).save(image_png,'PNG')
  img = mpimg.imread(image_png)
  plt.imshow(img)
  display()
def process_images(folder):

    classes = [os.path.join(folder, d) for d in sorted(os.listdir(folder))]  # get list of all sub-folders in folder
    img_cnt = 0

    for class_x in classes:

        if os.path.isdir(class_x):

            # get paths to all the images in this folder
            images = [os.path.join(class_x, i) for i in sorted(os.listdir(class_x)) if i != '.DS_Store']

            for image in images:

                img_cnt = img_cnt + 1

                if(img_cnt % 1000 == 0):                # show progress
                    print("Processed %s images" % str(img_cnt))

                im = Image.open(image)
                im = im.resize(dimensions)   # resize image according to dimensions set

                im = make_greyscale_white_bg(im, 127, 127, 127) # turn grey background (if any) to white, and
                                                                  # convert into greyscale image with 1 channel

                im = invert_colors(im)
                im.save(image)   # overwrite previous image file with new image

    print("Finished processing images, images found = ")
    print(img_cnt)
Beispiel #5
0
 def gen_data2(self,input_byte,input_path):
     img = Image.open(input_byte)
     img = img.resize((self.input_shape[0],self.input_shape[1]))
     
     img = self.pad_and_bg(img)
     
     blur_rad = np.random.normal(loc=0.0, scale=2, size=None)
     img = img.filter(ImageFilter.GaussianBlur(blur_rad))
    
     enhancer_contrat = ImageEnhance.Contrast(img)
     enhancer_color = ImageEnhance.Color(img)
     enhancer_brightness = ImageEnhance.Brightness(img)
     contrast_factor = np.random.normal(loc=1.0, scale=0.5, size=None)
     brightness_factor = np.random.normal(loc=1.0, scale=0.5, size=None)
     color_factor = np.max([0,1-abs(np.random.normal(loc=0, scale=0.5, size=None))])
     
     img = enhancer_contrat.enhance(contrast_factor)
     img = enhancer_brightness.enhance(brightness_factor)
     img = enhancer_color.enhance(color_factor)
     # img.save('test_blur.png')
     img = np.asarray(img)/127.5-1
     t = os.path.dirname(input_path)[-1:]
     # print(t,input_path)
     switcher = {
         '1': [1,0,0,0,0,0,0],
         '2': [0,1,0,0,0,0,0],
         '3': [0,0,1,0,0,0,0],
         '4': [0,0,0,1,0,0,0],
         '5': [0,0,0,0,1,0,0],
         '6': [0,0,0,0,0,1,0],
         '0': [0,0,0,0,0,0,1],
     }
     target = switcher.get(t)
     # print(t)
     return img,target
Beispiel #6
0
def nbread(imagefile):
    """
        - Purpose
            Read an image from a file to a numpy array.
        - Synopsis
            arr = nbread(imagefile)
        - Input
            imagefile: Image file path.
        - Output
            arr: numpy array representing an image.

    """

    image_path = findImageFile(imagefile)
    with Image.open(image_path) as image:         
        im_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
        bands = 3
        if image.mode == 'RGBA':
            im_arr = im_arr.reshape((image.size[1], image.size[0], 4))
        elif image.mode == 'L': 
            im_arr = im_arr.reshape((image.size[1], image.size[0]))
        elif image.mode == 'RGB':
            im_arr = im_arr.reshape((image.size[1], image.size[0], 3))
        elif image.mode == '1':
            print('does not support bit mode')
            return None
        else:
            im_arr = im_arr.reshape((image.size[1], image.size[0], 3))
    return im_arr
Beispiel #7
0
def process_images(folder):

    classes = [os.path.join(folder, d) for d in sorted(os.listdir(folder))
               ]  # get list of all sub-folders in folder
    img_cnt = 0

    for class_x in classes:

        if os.path.isdir(class_x):

            # get paths to all the images in this folder
            images = [
                os.path.join(class_x, i) for i in sorted(os.listdir(class_x))
                if i != '.DS_Store'
            ]

            for image in images:

                img_cnt = img_cnt + 1

                if (img_cnt % 1000 == 0):
                    print("Processed %s images" % str(img_cnt))

                im = Image.open(image)
                im = im.resize(
                    dimensions)  # resize image according to dimensions set
                im.save(image)  # overwrite previous image file with new image

    print("Finished processing images, images found = ")
    print(img_cnt)
Beispiel #8
0
def rotate_image(filepath):
    '''Phones rotate images by changing exif data, 
    but we really need to rotate them for processing'''

    image = Image.open(filepath)
    try:
        for orientation in ExifTags.TAGS.keys():
            if ExifTags.TAGS[orientation] == 'Orientation':
                break
            exif = dict(image._getexif().items())

        if exif[orientation] == 3:
            print('ROTATING 180')
            image = image.rotate(180, expand=True)
        elif exif[orientation] == 6:
            print('ROTATING 270')
            image = image.rotate(270, expand=True)
        elif exif[orientation] == 8:
            print('ROTATING 90')
            image = image.rotate(90, expand=True)
        image.save(filepath)
        image.close()
    except (AttributeError, KeyError, IndexError):
        # cases: image don't have getexif
        pass
    return (image)
Beispiel #9
0
 def test(self):
     label = {
         0: '1',
         1: '2',
         2: '3',
         3: '4',
         4: '5',
         5: 'x',
         6: '0',
     }
    
     i = np.random.randint(0,len(self.pathlisttest))
     input_img = Image.open(self.pathlisttest[i])
     transformed_pil,plot_pil,cropped_data = self.CamScan.cropAll(input_img,10)
     input_shape = self.input_shape
     batch_data = np.zeros((len(cropped_data),input_shape[0],input_shape[1],input_shape[2]))
      
     for index in range(len(cropped_data)):
         batch_data[index,:,:,:]=np.asarray(cropped_data[index]['image'].resize((self.input_shape[0],self.input_shape[1])))
 
     batch_data = (batch_data/127.5)-1
     result = self.model.predict(batch_data)
     result = np.argmax(result,axis=1)
     result2 = []
     for index in range(len(cropped_data)):
         result2.append(label[result[index]])
     final_img = self.CamScan.plot_result(plot_pil,result2)
     final_img.save(r'images/output_test/'+'test.jpg')
def directDownload(url):
    request = rlib.Request(url)
    response = rlib.urlopen(request)
    data = response.read()
    args = []
    split = url.split('.')
    args.append(split[-1])
    print("Image type: " + args[0])

    img = Image.open(io.BytesIO(data))
    size = img.size
    print("Image size: " + str(size))
    fname = "temp." + args[0]

    #resize image if needed
    if (size[0] > 1500 or size[1] > 1500):
        print("resizing img")
        max = np.maximum(size[0], size[1])
        divisor = float(max // 1500)
        newWidth = int(size[0] / divisor)
        newHeight = int(size[1] / divisor)
        img = img.resize((newWidth, newHeight), Image.ANTIALIAS)
        print("resized")

    try:
        img.save(fname)
        print("Saved input picure as temp." + args[0])
    except:
        print("Failed to save image")
        args[0] = "fail"
    return args
Beispiel #11
0
def visualise_baseline_mix(LL, X, mask, t=0, figsize=(10, 10), filename=None):
    # Unpack X_tensor
    lon = X[:, t, :mask[t], 0].squeeze().numpy() * lonstd + lonmean
    lat = X[:, t, :mask[t], 1].squeeze().numpy() * latstd + latmean

    fig = plt.figure(figsize=figsize)
    # Plot Copenhagen
    cph_img = np.asarray(Image.open('images/cph_2.png').convert("L"))
    plt.imshow(cph_img, extent=extent, aspect=aspect, cmap='gray')
    plt.imshow(LL,
               interpolation='bicubic',
               cmap='seismic',
               aspect='auto',
               extent=extent,
               vmin=-7,
               vmax=2,
               alpha=0.7,
               origin='lower')
    plt.scatter(x=lon, y=lat, color='k', s=30)

    # Save figure
    if filename is not None:
        plt.savefig(filename, bbox_inches='tight')
    else:
        plt.show()
def process_image(data, folder):
    images = np.ndarray([len(data), 32, 96, 1], dtype='int32')
    labels = np.ndarray([len(data), 6], dtype='int32')
    folder_name = folder
    l = len(data)

    for i in range(l) :
        image = data[i]
        image_name = dataset_location + folder_name + '/' + image['filename']

        img = Image.open(image_name)
        img = img.resize((96,32), PIL.Image.ANTIALIAS)
        img = np.asarray(img, dtype="int32")
        img = np.dot(img, [[0.2989],[0.5870],[0.1140]])

        no_of_digits = len(image['boxes'])
        if no_of_digits > 5:
            continue

        dig = np.array([])
        dig = np.append(dig, no_of_digits)

        for j in range(no_of_digits) :
            digit = image['boxes'][j]['label']
            dig = np.append(dig, digit)

        zeros = 5 - no_of_digits
        for z in range(zeros) :
            dig = np.append(dig, 0)

        images[i] = img
        labels[i] = dig
        
    return(images, labels)
Beispiel #13
0
def read_image(filename, flatten=False, dtype=np.float32):
    img = Image.open(filename)
    img.load()
    data = np.asarray(img, dtype=dtype)
    if flatten:
        data = data.mean(axis=-1)
    return data
Beispiel #14
0
 def test(self):
     #template v6
     crop_col = [1525, 1588, 1651, 1714, 1777, 1840, 1903, 1966, 2029, 2092, 2155, 2218, 2281, 2344, 2407, 2470, 2532, 2596, 2658, 2722,2798]
     crop_row = [892, 936, 981, 1026, 1071, 1115, 1160, 1205, 1250, 1294, 1339, 1384, 1429, 1473, 1518, 1563, 1608, 1653, 1697, 1742, 1787, 1832, 1876, 1921, 1966, 2011, 2055, 2100, 2145, 2190, 2235, 2279, 2324, 2369, 2414, 2458, 2503, 2548, 2593, 2637, 2682, 2727, 2772, 2817, 2861, 2906, 2951, 2996, 3040, 3085, 3130, 3175, 3219, 3264, 3309, 3354, 3399]
     label = {
         0: '0',
         1: '1',
         2: '2',
         3: '3',
         4: '4',
         5: '5',
         6: 'X',
     }
    
     i = np.random.randint(0,len(self.pathlisttest))
     input_img = Image.open(self.pathlisttest[i])
     transformed_pil,plot_pil,cropped_data = self.CamScan.cropAll(input_img,crop_col,crop_row,10)
     input_shape = self.input_shape
     batch_data = np.zeros((len(cropped_data),input_shape[0],input_shape[1],input_shape[2]))
      
     for index in range(len(cropped_data)):
         batch_data[index,:,:,:]=np.asarray(cropped_data[index]['image'].resize((self.input_shape[0],self.input_shape[1])))
 
     batch_data = (batch_data/127.5)-1
     result = self.model.predict(batch_data)
     result = np.argmax(result,axis=1)
     result2 = []
     for index in range(len(cropped_data)):
         result2.append(label[result[index]])
     final_img = self.CamScan.plot_result(plot_pil,result2,crop_col,crop_row)
     final_img.save(r'images/output_test/'+ os.path.basename(self.pathlisttest[i]))
Beispiel #15
0
def parse_img(num_files, DIR, f):
	current_clothes = np.zeros(shape=(int(num_files),784),dtype=object)
	for i in range(0,num_files):
	        img = Image.open(DIR+str(f)+'_'+str(i)+'.png')
	        img_arr = np.array(img.getdata(), np.uint8)
	        current_clothes[i,:] = img_arr
	return current_clothes
Beispiel #16
0
    def __init__(self, img_path):

        response = request.urlopen(url)
        image_data = response.read()
        self.image = Image.open(BytesIO(image_data))
        self.get_exif_data()
        super(ImageMetaData, self).__init__()
Beispiel #17
0
def transformAllImages(path: str, set_type: str) -> None:

    if path is None or not os.path.isdir(path):
        raise Exception(f"No path available for source: {path}")

    if set_type == "val":
        transform = transformValImage

    elif set_type == "train":
        transform = transformTrainImage
    else:
        return

    def isImg(fn: str) -> bool:
        return '.jpg' in fn.casefold()

    img_name_list = list(filter(isImg, os.listdir(path)))

    for img_name in img_name_list:
        img_path = os.path.join(path, img_name)
        with Image.open(img_path) as img:
            if img.mode == 'L':
                img = transforms.Grayscale(num_output_channels=3)(img)
            if img.mode == 'CMYK':
                img = img.convert('RGB')
            try:
                img = transform(img)
            except Exception as e:
                raise Exception(f"{e}\n{img_name}")

            img = transforms.ToPILImage()(img)
            img.save(img_path)
Beispiel #18
0
 def pad_and_bg(self,img):
     
     bg_img = np.asarray(Image.open(io.BytesIO( np.random.choice(self.bg_buffer))))
     ret_img = img
     
     
     pad_top = int(abs(np.random.normal(0,self.pad_param)))
     pad_bottom = int(abs(np.random.normal(0,self.pad_param)))
     pad_left = int(abs(np.random.normal(0,self.pad_param)))
     pad_right = int(abs(np.random.normal(0,self.pad_param)))
     
     
     # trim_top = int(abs(np.random.normal(0,self.trim_param)))
     # trim_bottom = int(abs(np.random.normal(0,self.trim_param)))
     # trim_left = int(abs(np.random.normal(0,self.trim_param)))
     # trim_right = int(abs(np.random.normal(0,self.trim_param)))
     
     ret_img = cv2.copyMakeBorder( np.asarray(ret_img), pad_top, pad_bottom, pad_left, pad_right, cv2.BORDER_CONSTANT,value=(255,255,255))
     
     #mask
     mask_img = np.zeros((img.size[0],img.size[1],3))
     # mask_2 = Image.fromarray(mask_img.astype('uint8')).rotate(rotate_param,resample = Image.NEAREST,expand = True, fillcolor = (255,255,255))
     mask_3 = cv2.copyMakeBorder( np.asarray(mask_img), pad_top, pad_bottom, pad_left, pad_right, cv2.BORDER_CONSTANT,value=(255,255,255))
     
     ret_img = cv2.resize(ret_img, dsize=(img.size[0], img.size[1]))
     bg_img = cv2.resize(bg_img, dsize=(img.size[0], img.size[1]))
     mask_3 = cv2.resize(mask_3, dsize=(img.size[0], img.size[1]))
     
     mask_3 = mask_3/255
     ret_img = ret_img*(1-mask_3) + bg_img*mask_3
     ret_img = Image.fromarray(ret_img.astype('uint8'))
     
     return  ret_img
Beispiel #19
0
 def pad_and_bg(self,img):
     
     bg_img = np.asarray(Image.open(io.BytesIO( np.random.choice(self.bg_buffer))))
     ret_img = img
     rows,cols = img.size
     
     s_x = int(np.random.normal(0,6))
     s_y = int(np.random.normal(0,10))
     
     M = np.float32([[1,0,s_x],[0,1,s_y]])
     ret_img = cv2.warpAffine(np.asarray(ret_img),M,(cols,rows),borderMode = cv2.BORDER_CONSTANT,borderValue=(255,255,255))
     
     
    
     
     # ret_img = cv2.copyMakeBorder( np.asarray(ret_img), pad_top, pad_bottom, pad_left, pad_right, cv2.BORDER_CONSTANT,value=(255,255,255))
     
     #mask
     mask_img = np.zeros((img.size[0],img.size[1],3))
     # mask_2 = Image.fromarray(mask_img.astype('uint8')).rotate(rotate_param,resample = Image.NEAREST,expand = True, fillcolor = (255,255,255))
     # mask_3 = cv2.copyMakeBorder( np.asarray(mask_img), pad_top, pad_bottom, pad_left, pad_right, cv2.BORDER_CONSTANT,value=(255,255,255))
     mask_3 = cv2.warpAffine(np.asarray(mask_img),M,(cols,rows),borderMode = cv2.BORDER_CONSTANT,borderValue=(255,255,255))
     
     # ret_img = cv2.resize(ret_img, dsize=(img.size[0], img.size[1]))
     bg_img = cv2.resize(bg_img, dsize=(img.size[0], img.size[1]))
     # mask_3 = cv2.resize(mask_3, dsize=(img.size[0], img.size[1]))
     
     mask_3 = mask_3/255
     ret_img = ret_img*(1-mask_3) + bg_img*mask_3
     ret_img = Image.fromarray(ret_img.astype('uint8'))
     
     return  ret_img
def rotate_image(filepath):
    '''
    Rotates images from cellphones if needed by checking exif data, prior to processing. 
    '''
    image = Image.open(filepath)
    try:
        for orientation in ExifTags.TAGS.keys():
            if ExifTags.TAGS[orientation] == 'Orientation':
                break
            exif = dict(image._getexif().items())

        if exif[orientation] == 3:
            print('ROTATING 180')
            image = image.rotate(180, expand=True)
        elif exif[orientation] == 6:
            print('ROTATING 270')
            image = image.rotate(270, expand=True)
        elif exif[orientation] == 8:
            print('ROTATING 90')
            image = image.rotate(90, expand=True)
        image.save(filepath)
        image.close()
    except (AttributeError, KeyError, IndexError):
        # cases: image don't have getexif
        pass
    return (image)
Beispiel #21
0
def checkValidateCode():
    img = Image.open('code.png').convert('L')
    ret, img = cv2.threshold(np.array(img), 125, 255, cv2.THRESH_BINARY)
    img = Image.fromarray(img.astype(np.uint8))
    pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe'
    code = pytesseract.image_to_string(img)

    return code.strip()
Beispiel #22
0
def displayLettersAsImage(folders_list):
    for folder in folders_list:
        letter = folder[-1]
        image = random.choice(os.listdir(folder))
        path = os.path.join(folder, image)
        #can't use iPython  display on windows (api problmen)
        img = Image.open(path)
        img.show()
        print(letter)
Beispiel #23
0
 def preprocess_image(self, img_path):
     """
     Used to perform some minor preprocessing on the image before inputting into the network.
     """
     im = Image.open(img_path)
     im = im.resize((IM_WIDTH, IM_HEIGHT))
     im = np.array(im) / 255.0
     
     return im
Beispiel #24
0
    def test_screen(self):

        self.driver.get("http://the-internet.herokuapp.com/")
        self.driver.find_element_by_partial_link_text("File Download").click()
        self.driver.save_screenshot("screen_file3.png")
        time.sleep(3)
        size = (0, 0, 680, 400)
        im1 = Image.open("screen_file3.png")
        im2 = im1.crop(size)
        im2.save('element_image.png')
Beispiel #25
0
def load_images(file):
    f = open(file)
    images = []
    for line in f:
        path = "data/images/" + line.rstrip()
        img = Image.open(path)
        img = img.resize((224, 224))
        images.append(np.array(img))
    f.close()
    return np.array(images)
Beispiel #26
0
    def gen_data(self,input_byte,input_path):
        img = Image.open(input_byte)
        img = img.resize((self.input_shape[0],self.input_shape[1]))
        # img = self.pad_and_bg(img)
        # rotate_factor = np.random.normal(loc=1.0, scale=10, size=None)
        # img = img.rotate(rotate_factor)
        # flip_flag = np.random.randint(0,1)
        # mirror_flag = np.random.randint(0,1)
        # gray_flag = np.random.randint(0,1)
        # if(gray_flag):
        #     img = img.convert('LA')
        # if(flip_flag):
        #     img = ImageOps.flip(img)
        # if(mirror_flag):
        #     img = ImageOps.mirror(img)
            
        blur_rad = np.random.normal(loc=0.0, scale=2, size=None)
        img = img.filter(ImageFilter.GaussianBlur(blur_rad))
        
        enhancer_contrat = ImageEnhance.Contrast(img)
        enhancer_brightness = ImageEnhance.Brightness(img)
        enhancer_color = ImageEnhance.Color(img)
        contrast_factor = np.random.normal(loc=1.0, scale=0.5, size=None)
        color_factor = np.max([0,1-abs(np.random.normal(loc=0, scale=0.5, size=None))])

        rotate_factor = np.random.normal(loc=0, scale=0.17, size=None)
        translate_factor_hor = np.random.normal(loc=0, scale=5, size=None)
        translate_factor_ver = np.random.normal(loc=0, scale=5, size=None)
        brightness_factor = np.random.normal(loc=1.0, scale=0.5, size=None)

        img = enhancer_contrat.enhance(contrast_factor)
        img = enhancer_brightness.enhance(brightness_factor)
        img = enhancer_color.enhance(color_factor)
        img = ImageChops.offset(img, int(translate_factor_hor), int(translate_factor_ver))
        img = img.rotate(np.rad2deg(rotate_factor))
        
        img.save('test_blur.png')
        img = np.asarray(img)/127.5-1
        t = os.path.dirname(input_path)[-1:]
        # print(t,input_path)
        switcher = {
            '0': [1,0,0,0,0,0,0],
            '1': [0,1,0,0,0,0,0],
            '2': [0,0,1,0,0,0,0],
            '3': [0,0,0,1,0,0,0],
            '4': [0,0,0,0,1,0,0],
            '5': [0,0,0,0,0,1,0],
            '6': [0,0,0,0,0,0,1],
           
        
            
        }
        target = switcher.get(t)
        # print(t)
        return img,target
Beispiel #27
0
def set_image_dpi(file_path):
    im = Image.open(file_path)
    length_x, width_y = im.size
    factor = max(1, int(IMAGE_SIZE / length_x))
    size = factor * length_x, factor * width_y
    # size = (1800, 1800)
    im_resized = im.resize(size, Image.ANTIALIAS)
    temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg')
    temp_filename = temp_file.name
    im_resized.save(temp_filename, dpi=(300, 300))
    return temp_filename
def load_and_resize_image(image_path, target_size=None) -> Image:
    '''
    # Returns
    # The loaded and resized PIL image
    '''
    img = Image.open(image_path)

    if target_size is None:
        return img
    else:
        return ImageOps.fit(img, target_size, Image.ANTIALIAS)
Beispiel #29
0
    def __getitem__(self, idx):

        image_path = os.path.join(self.images_path, self.images_name[idx])
        image = Image.open(image_path)
        if len(image.getbands()) == 4:  # Fix in png.
            im2arr = np.array(image)
            image = Image.fromarray(im2arr[:, :, :-1])
        image = image.resize((215, 215), Image.BILINEAR)
        X = self.transform(image)

        return X
Beispiel #30
0
def convert_png_to_gif(n_image,
                       gifdir='figures/frame_dir',
                       name='multiz',
                       fps=2):
    images = []
    for i in range(n_image):
        print(i)
        a = Image.open(gifdir + '/vol_' + str(i) + '.png')
        images.append(a)

    imageio.mimsave(gifdir + '/' + name + '.gif', images, fps=fps)
Beispiel #31
0
def resize_image(path, size):
    for i in dir:
        if os.path.isfile(path + item):
            image = Image.open(path +
                               i)  #opening any particular image in a file
            f, e = os.path.splitext(path + i)
            re_image = image.resize(
                size, Image.ANTIALIAS)  #resizing the image with assigned size.
            re_image.save(
                f + ' resized.png', 'PNG', quality=90
            )  #saving the resized image in png format by assigning name.
def augment_by_rotations(folder, prev_cnt):

    classes = [os.path.join(folder, d) for d in sorted(os.listdir(folder))]  # get list of all sub-folders in folder

    for path_to_folder in classes:

        if os.path.isdir(path_to_folder):
            images = [os.path.join(path_to_folder, i) for i in sorted(os.listdir(path_to_folder)) if i != '.DS_Store']
            filename = prev_cnt
            for image in images:

                im = Image.open(image)

                # make 4 copies of each image, with random rotations added in
                random_rotate(im, 4, filename, path_to_folder)
                filename = filename + 4

            print("Finished augmenting " + path_to_folder)
def test_rotations():

    img = Image.open("Train/172/bcc000002.bmp")

    #img = img.rotate(30)

    img = img.resize(dimensions)



    rot = make_greyscale_white_bg(img, 127, 127, 127)

    rot = invert_colors(rot)
    c_color = rot.getpixel((0, 0))
    rot = rotate_img(rot, 10, c_color)

    w, h = rot.size
    rot.show()
        return np.array(return_image)

def display(image) : 
    if type(image) is type([]) : 
        for images in image :
            matplotlib.pyplot.figure()
            imshow(images,cmap=matplotlib.pyplot.get_cmap('gray'))
    else : 
        imshow(image,cmap=matplotlib.pyplot.get_cmap('gray'))


# #original image

# In[170]:

image = np.array(Image.open('sample images/sample_image.jpg')) 

#imshow(image,cmap=matplotlib.pyplot.get_cmap('grey'))
impr = image_processing()
image = impr.rgb_to_greyscale(image)
display(image)


# #vertical edge detection

# In[171]:

def vertical_edge_detection(self,image) : 
    kernel = [1,[[-1,0,1],
                 [-1,0,1],
                 [-1,0,1]]]
    os.path.join(root, d) for d in sorted(os.listdir(root))
    if os.path.isdir(os.path.join(root, d))]
  if len(data_folders) != num_classes:
    raise Exception(
      'Expected %d folders, one per class. Found %d instead.' % (
        num_classes, len(data_folders)))
  print(data_folders)
  return data_folders
  
train_folders = maybe_extract(train_filename)
test_folders = maybe_extract(test_filename)

#%% Problem 1

from PIL import Image
image=Image.open('MDEtMDEtMDAudHRm.png')
image.show()


#%%
image_size = 28  # Pixel width and height.
pixel_depth = 255.0  # Number of levels per pixel.

def load_letter(folder, min_num_images):
  """Load the data for a single letter label."""
  image_files = os.listdir(folder)
  dataset = np.ndarray(shape=(len(image_files), image_size, image_size),
                         dtype=np.float32)
  image_index = 0
  print(folder)
  for image in os.listdir(folder):