示例#1
0
def save_img(path,
             x,
             data_format=None,
             file_format=None,
             scale=True,
             **kwargs):
  """Saves an image stored as a Numpy array to a path or file object.

  Arguments:
      path: Path or file object.
      x: Numpy array.
      data_format: Image data format,
          either "channels_first" or "channels_last".
      file_format: Optional file format override. If omitted, the
          format to use is determined from the filename extension.
          If a file object was used instead of a filename, this
          parameter should always be used.
      scale: Whether to rescale image values to be within `[0, 255]`.
      **kwargs: Additional keyword arguments passed to `PIL.Image.save()`.
  """
  if data_format is None:
    data_format = backend.image_data_format()
  image.save_img(path,
                 x,
                 data_format=data_format,
                 file_format=file_format,
                 scale=scale, **kwargs)
def save_img(path,
             x,
             data_format=None,
             file_format=None,
             scale=True,
             **kwargs):
    """Saves an image stored as a Numpy array to a path or file object.

  Arguments:
      path: Path or file object.
      x: Numpy array.
      data_format: Image data format,
          either "channels_first" or "channels_last".
      file_format: Optional file format override. If omitted, the
          format to use is determined from the filename extension.
          If a file object was used instead of a filename, this
          parameter should always be used.
      scale: Whether to rescale image values to be within `[0, 255]`.
      **kwargs: Additional keyword arguments passed to `PIL.Image.save()`.
  """
    if data_format is None:
        data_format = backend.image_data_format()
    image.save_img(path,
                   x,
                   data_format=data_format,
                   file_format=file_format,
                   scale=scale,
                   **kwargs)
def save_image(image_npy, dest_folder_path=os.getcwd(), dest_filename="img.bmp"):
    if image_npy is None:
        raise Exception("The provided numpy Array is None")
    if not len(image_npy.shape) in (2, 3):
        raise Exception("The Number od dimensions of the provided image is neither 2 nor 3.")
    if not os.path.isdir(dest_folder_path):
        raise Exception("The provided folder path is not existent")
    if dest_filename in os.listdir(dest_folder_path):
        raise Exception("A file with the same name is already present in this folder")
    pil_img = array_to_img(image_npy)
    save_img(os.path.join(dest_folder_path, dest_filename), pil_img)
def data_augment():
    root_dir = os.path.join(DATA_PATH, "Image")
    for parents, dirnames, filenames in os.walk(root_dir):
        if parents != root_dir:
            #print("parents = ", parents)
            #print("dirnames = ", dirnames)
            #print("flienames = ", filenames)
            name_store = filenames
            #print("name_store = ", name_store)
            new_name_store = []
            for i in range(
                (factor - 1) *
                    len(name_store)):  #一共要生成factor * len(name_store)个新名字
                rand_num = np.random.randint(0, len(name_store))
                ext = os.path.splitext(name_store[rand_num])[-1]
                src = os.path.join(parents, name_store[rand_num])
                new_name = str(np.random.randint(
                    10000, 100000)) + ext  #新名字的范围在10000~99999
                for j in range(len(new_name_store)):  #找到一个独一无二的新名字
                    if new_name == new_name_store[j]:  #如果遇到重复的名字
                        new_name = str(np.random.randint(
                            10000, 1000000)) + ext  #生成新名字
                        j = 0  #再次遍历new_name_store
                new_name_store.append(new_name)
                dst = os.path.join(parents, new_name)
                datagen = ImageDataGenerator(rotation_range=40,
                                             width_shift_range=0.2,
                                             height_shift_range=0.2,
                                             shear_range=0.2,
                                             zoom_range=0.2,
                                             horizontal_flip=True,
                                             fill_mode="nearest")
                img = image.load_img(src)
                x = image.img_to_array(img)
                img_width = x.shape[0]
                img_height = x.shape[1]
                x = x.reshape((1, ) + x.shape)

                for batch in datagen.flow(x, batch_size=16):
                    image.save_img(dst,
                                   batch.reshape(img_width, img_height, 3),
                                   file_format=ext[1:])
                    print("Add: ", dst)

                    break

                ##开始更改csv文件
                change_csv(os.path.join("Image",
                                        os.path.split(parents)[-1]), new_name)
def stitch_images_and_save(filepath_list: list, stitched_folder: str,
                           split_locations: tuple = IMAGE_SPLIT_LOCATIONS):
    print("\n\nNew Stitch:")
    if not os.path.isdir(stitched_folder):
        os.makedirs(stitched_folder)

    if re.search("Alge", filepath_list[0]):
        stitched_filename = "stitched_Alge"
    elif re.search("Zwiebelzelle", filepath_list[0]):
        stitched_filename = "stitched_Zwiebelzelle"
    else:
        stitched_filename = "stitched"

    split_images_list = []

    for filepath in filepath_list:
        print(filepath)
        split_images_list.append(split_image(filepath, split_locations))
        filename = filename_from_path(filepath)
        stitched_filename += "_" + filename.split(".")[0][8:]
    stitched_filename += ".bmp"
    stitched_filepath = os.path.join(stitched_folder, stitched_filename)

    rearranged_images = [[], [], [], []]  # [image3, image4, image2, image1]
    for tup in split_images_list:
        if tup[1] == 1:
            rearranged_images[3] = tup[0]
        elif tup[1] == 2:
            rearranged_images[2] = tup[0]
        elif tup[1] == 3:
            rearranged_images[0] = tup[0]
        elif tup[1] == 4:
            rearranged_images[1] = tup[0]
        else:
            print(f"{Fore.RED}[ERROR]  Wrong image group found. "
                  f"The image group should be '1' or '2' or '3' or '4'{Style.RESET_ALL}")
            sys.exit(-2)

    merged_img1 = np.concatenate((rearranged_images[0], rearranged_images[1]), axis=1)
    merged_img2 = np.concatenate((rearranged_images[2], rearranged_images[3]), axis=1)
    img_height1, img_height2 = merged_img1.shape[0], merged_img2.shape[0]
    i, j = split_locations[8], split_locations[9]

    split_merged_img1 = (np.array_split(merged_img1, [img_height1-i], axis=0))[0]
    split_merged_img2 = (np.array_split(merged_img2, [220], axis=0))[1]
    merged_total = np.concatenate((split_merged_img1, split_merged_img2), axis=0)
    save_img(stitched_filepath, merged_total)
示例#6
0
def save_img(path,
             x,
             data_format=None,
             file_format=None,
             scale=True, **kwargs):
    if data_format is None:
        data_format = backend.image_data_format()
    return image.save_img(path,
                          x,
                          data_format=data_format,
                          file_format=file_format,
                          scale=scale, **kwargs)
def save_img(path,
             x,
             data_format=None,
             file_format=None,
             scale=True, **kwargs):
    if data_format is None:
        data_format = backend.image_data_format()
    return image.save_img(path,
                          x,
                          data_format=data_format,
                          file_format=file_format,
                          scale=scale, **kwargs)
示例#8
0
def predict(path_to_image: str):
    # load the model we saved
    model = MnistCnnModel(num_classes, (img_width, img_height), 3,
                          './final.h5').get_trained_model()
    img = image.load_img(path_to_image,
                         target_size=(img_height, img_width),
                         color_mode='rgba')
    img.load()
    background = Image.new('RGBA', (72, 72), (71, 113, 77, 255))
    background.paste(img, mask=img.split()[3])  # 3 is the alpha channel
    image.save_img('./temp.png', background, file_format='png')
    # background.convert('RGB') - doesn't work here but works in load_img

    x = image.load_img('./temp.png', color_mode='rgb')
    x = image.img_to_array(x)
    x = np.expand_dims(x, axis=0)

    images = np.vstack([x])
    classes = model.predict_classes(images, batch_size=1)

    # print the classes, the images belong to
    with open(settings.JSON_CLASSES, 'r') as f:
        classes_dict = ujson.load(f)
        print(f'classes is: {classes_dict[str(classes[0])]}')
示例#9
0
def main():
    # sym, arg_params, aux_params = mx.model.load_checkpoint("base_net", 0)
    # net.load_parameters('testnet.params')
    save_img()
    K.function()
    pass
示例#10
0
def saveResult(save_path, npyfile):
    for i, item in enumerate(npyfile):
        #img = item[:, :, 1]
        save_img(os.path.join(save_path, "%d_predict.png" % i), item)