Пример #1
1
import image_slicer
import os 
# image_slicer.slice('CarPlateFull/31.jpg', 50)

# to crop all image in the directory into smaller images
subdirs = [x[0] for x in os.walk("CarPlateFull")]                                                                            
for subdir in subdirs:                                                                                            
        files = os.walk(subdir).next()[2]                                                                             
        if (len(files) > 0):                                                                                          
            for file in files:
                print file
                tiles = image_slicer.slice("CarPlateFull/"+file, 50, save=False)
                image_slicer.save_tiles(tiles, directory='CarPlateFull/Tiled', prefix=file)
Пример #2
0
 def test_all_files_saved(self):
     save_tiles(self.tiles, prefix="x", directory=TEST_DIR, format="gif")
     self.assertEqual(
         sorted(os.listdir(TEST_DIR)),
         [
             "x_01_01.gif",
             "x_01_02.gif",
             "x_01_03.gif",
             "x_01_04.gif",
             "x_01_05.gif",
             "x_02_01.gif",
             "x_02_02.gif",
             "x_02_03.gif",
             "x_02_04.gif",
             "x_02_05.gif",
             "x_03_01.gif",
             "x_03_02.gif",
             "x_03_03.gif",
             "x_03_04.gif",
             "x_03_05.gif",
             "x_04_01.gif",
             "x_04_02.gif",
             "x_04_03.gif",
             "x_04_04.gif",
             "x_04_05.gif",
         ],
     )
Пример #3
0
def getSlicedFeatures(path, name):

    size = 0

    if name == "ts":
        size = 144
    elif name == "ts1":
        size = 48
    elif name == "ts2":
        size = 57
    elif name == "ts3":
        size = 39
    elif name == "tr":
        size = 264
    elif name == "tr1":
        size = 88
    elif name == "tr2":
        size = 88
    elif name == "tr3":
        size = 88

    curr_dir = os.getcwd()
    folder_path = path + "/"
    save_path = curr_dir + "/dataset2/sliced/"

    N = 4
    dataset_sub = np.zeros(size * 6).reshape((size, 6))
    i = 0
    for filename in os.listdir(folder_path):
        print("filename is: " + filename)
        tiles = image_slicer.slice(folder_path + filename, N, save=False)
        image_slicer.save_tiles(tiles, directory=save_path)
        dataset_sub[i] = getFeatures("sub", name)

    return dataset_sub
Пример #4
0
def call_game(ia_final_move, squareside, allcase, gamemode, fenetre):
    tiles = image_slicer.slice("/Users/gkuma/Downloads/photo_" +
                               str(squareside * 100) + "_.jpg",
                               squareside * squareside,
                               save=False)
    image_slicer.save_tiles(tiles,
                            directory='/Users/gkuma/Downloads/',
                            prefix='')
    replay = 1
    while (replay == 1):
        blocks = []
        blocks = utils.build_board(allcase, squareside, blocks, fenetre)
        fond = pygame.image.load("/Users/gkuma/Downloads/background.jpg")
        fenetre.blit(fond, (0, 0))
        first_draw(squareside, fenetre, blocks, gamemode)
        pygame.display.flip()
        if gamemode == 'ia':
            main_loop(ia_final_move, squareside, fenetre, blocks, fond)
        if gamemode == 'solo':
            main_loop_solo(squareside, fenetre, blocks, fond)
        pygame.time.wait(3000)
        menu_items = ('Replay', 'MainMenu', 'Quit')
        pygame.display.set_caption('Replay')
        replay_menu = ReplayMenu(fenetre, menu_items)
        # return the choice enter in the menu
        replay = replay_menu.run()
    if replay == 2:
        replay = 1
    return replay
Пример #5
0
def sliceImages(foldername, image_name):
    directory = root + "\\" + foldername + "\\"
    os.makedirs(directory)
    image_tiles = image_slicer.slice(image_name, 50, save=False)
    image_slicer.save_tiles(image_tiles,
                            directory=directory,
                            prefix=image_name)
Пример #6
0
def uploader():
    if request.method == 'POST':
        f = request.files['file']
        #files = glob.glob('/Users/liule/att/lei-connector-cooler/test/*')
        #for f in files:
        #os.remove(f)
        #f.save(secure_filename(f.filename))
        #shutil.rmtree('/Users/liule/att/lei-connector-cooler/test')
        #os.mkdir('/Users/liule/att/lei-connector-cooler/test')
        f.save(
            os.path.join(app.config['UPLOAD_FOLDER'],
                         secure_filename(f.filename)))
        for root, dirs, files in os.walk(
                "/Users/liule/att/lei-connector-cooler/test"):
            for filename in files:
                print(filename)
                tiles = image_slicer.slice(
                    '/Users/liule/att/lei-connector-cooler/test/' + filename,
                    4,
                    save=False)
                image_slicer.save_tiles(
                    tiles,
                    directory='/Users/liule/att/lei-connector-cooler/test',
                    prefix='slice' + filename)
        os.remove("/Users/liule/att/lei-connector-cooler/test/" +
                  secure_filename(f.filename))

        IMAGE = "/Users/liule/att/lei-connector-cooler/test"
        # if 'Image' in req_data:
        #  IMAGE  = req_data['Image']
        #print(request.headers)
        #data_headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}

        # create slice files here
        return render_template('/pages/connector_cooler.html')
Пример #7
0
def slicing_of_image(dimensions, desired_size, image_path, resized_path,
                     sliced_path, image_type):
    #Calculation to equally slice up the image to the desired size
    number = dimensions[0] / desired_size
    x = math.log(number, 2)

    if dimensions[0] == desired_size:
        split = 2
    else:
        split = 2**(x * 2)

    for file in glob.glob(image_path + "/*" + image_type):
        imageName = file.split('\\')[6][
            0:
            -4]  #Change the values in regards to the position of the directory
        img = cv2.imread(file, -1)
        img = cv2.resize(img, dimensions, interpolation=cv2.INTER_AREA)
        os.chdir(resized_path)
        cv2.imwrite(imageName + image_type, img)

    for file in glob.glob(resized_path + "/*" + image_type):
        imageName = file.split('\\')[6][
            0:
            -4]  #Change the values in regards to the position of the directory
        tiles = image_slicer.slice(file, split, save=False)
        image_slicer.save_tiles(tiles,
                                directory=sliced_path,
                                prefix=imageName,
                                format=image_type[1:])
Пример #8
0
def slice_and_save(s_dir, t_dir, v_dir, n, m):
    # t_dir holds unsliced images, s_dir will contain sliced images, n is number of tiles
    for sd in get_subdirs(s_dir):
        print "SUB DIR: {}".format(sd)

        # Create sub-directories if they do not already exist
        if not os.path.exists(os.path.join(v_dir, sd)):
            os.makedirs(os.path.join(v_dir, sd))
        if not os.path.exists(os.path.join(t_dir, sd)):
            os.makedirs(os.path.join(t_dir, sd))

        # Iterate through all images and labels, slice, and save into t_dir, and v_dir
        for i, f in enumerate(get_file_names(os.path.join(s_dir, sd))):
            if i % m == 0:  # save to v_dir/sd/
                tiles = slice(f, n, save=False)
                save_tiles(tiles,
                           prefix=get_basename(f),
                           directory=os.path.join(v_dir, sd))
                print "{} sliced and saved to {}".format(
                    f, os.path.join(v_dir, sd))
            else:  # save to t_dir/sd/
                tiles = slice(f, n, save=False)
                save_tiles(tiles,
                           prefix=get_basename(f),
                           directory=os.path.join(t_dir, sd))
                print "{} sliced and saved to {}".format(
                    f, os.path.join(t_dir, sd))
        print "============================"
Пример #9
0
    def slice(self, portions):
        self.img_dir_path = self.slides_dir + "/image_2048"
        self.label_dir_path = self.slides_dir + "/label_2048"
        self.sliced_img_path = self.slides_dir + "/image_1024"
        self.sliced_lbl_path = self.slides_dir + "/label_1024"

        for filename in os.listdir(self.img_dir_path):
            file_path = self.img_dir_path + '/' + filename
            tiles = image_slicer.slice(file_path, portions, save=False)
            filename_no_sufix = filename[:-4]
            # slice_name = staining + '_' + filename_no_sufix + '_Mask'
            image_slicer.save_tiles(tiles,
                                    directory=self.sliced_img_path,
                                    prefix=filename_no_sufix,
                                    format='PNG')
            portion_name = filename[-9:-4]
            mask_file_path = self.label_dir_path + "/" + filename  #[:-4] + "-labelled.png"
            # ipdb.set_trace()
            # mask_file_path_to_save = test_labels_1024_path + '/' + filename_no_sufix + '.png'

            tiles = image_slicer.slice(mask_file_path, portions, save=False)
            image_slicer.save_tiles(tiles,
                                    directory=self.sliced_lbl_path,
                                    prefix=filename_no_sufix,
                                    format='PNG')
Пример #10
0
def slice_img(orig_img, img_name, path_img_rot, angle, control):
    if control == 0:
        pos_x = 0
        pos_y = 0

        img_rot = cv.imread(os.path.join(path_img_rot + r'/' + img_name))
        cv.imwrite(os.path.join(path_tiles, img_name), img_rot)

        orig_img = detect_face_cnn(orig_img, img_name, angle, pos_x, pos_y)
        orig_img.save(path_output + r'/' + img_name)
        # cv.imwrite(os.path.join(path_output, img_name), orig_img)

    else:
        tiles = image_slicer.slice(path_img_rot + r'/' + img_name,
                                   2,
                                   save=False)
        image_slicer.save_tiles(tiles, directory=path_tiles, prefix='slice')

        slice_name = 'slice_01_01.png'
        pos_x = tiles[0].coords[0]
        pos_y = tiles[0].coords[1]
        orig_img = detect_face_cnn(orig_img, slice_name, angle, pos_x, pos_y)

        slice_name = 'slice_01_02.png'
        pos_x = tiles[1].coords[0]
        pos_y = tiles[1].coords[1]
        orig_img = detect_face_cnn(orig_img, slice_name, angle, pos_x, pos_y)

        orig_img.save(path_output + r'/' + img_name)

        tiles[0].image = Image.open(path_tiles + r'/' + 'slice_01_01.png')
        tiles[1].image = Image.open(path_tiles + r'/' + 'slice_01_02.png')

        image = image_slicer.join(tiles)
        image.save(path_result + r'/' + str(angle) + '_' + img_name)
Пример #11
0
def home(request):
    if request.method == 'POST' and request.FILES['myfile']:
        myfile = request.FILES['myfile']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        uploaded_file_url = fs.path(filename)
        tiles = image_slicer.slice(uploaded_file_url, 9, save=False)
        image_slicer.save_tiles(tiles,
                                directory='media/',
                                prefix='slice',
                                format='png')
        os.remove(uploaded_file_url)
        z = zipstream.ZipFile(mode='w', compression=zipstream.ZIP_DEFLATED)
        z.write('media/slice_01_01.png', 'slice_01_01.png')
        z.write('media/slice_01_02.png', 'slice_01_02.png')
        z.write('media/slice_01_03.png', 'slice_01_03.png')
        z.write('media/slice_02_01.png', 'slice_02_01.png')
        z.write('media/slice_02_02.png', 'slice_02_02.png')
        z.write('media/slice_02_03.png', 'slice_02_03.png')
        z.write('media/slice_03_01.png', 'slice_03_01.png')
        z.write('media/slice_03_02.png', 'slice_03_02.png')
        z.write('media/slice_03_03.png', 'slice_03_03.png')
        response = StreamingHttpResponse(z, content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename={}'.format(
            'files.zip')
        return response

    return render(request, 'core/simple_upload.html')
Пример #12
0
def preparation_of_image(dimensions, desired_size, image_path, resized_path,
                         sliced_path, image_type, predicted_path,
                         recombined_path, threshold):
    segmentation_model = tf.keras.models.load_model(
        "Model/UNetW.h5")  #Loading UNet Model
    #To determine how many portions to split to achieve desired size
    number = dimensions[0] / desired_size
    x = math.log(number, 2)
    if dimensions[0] == desired_size:
        split = 2
    else:
        split = 2**(x * 2)

    imageName = os.path.basename(
        os.path.normpath(image_path)
    )[:-4]  #Getting the test image name from the test image path
    img = cv2.imread(
        image_path + image_type,
        cv2.IMREAD_GRAYSCALE)  #Reading the test image in grayscale
    img = cv2.resize(img, dimensions, interpolation=cv2.INTER_AREA
                     )  #Resizing the test image into the correct size
    os.chdir(
        resized_path)  #Changing the directory for the test image to be saved
    cv2.imwrite(imageName + image_type, img)  #Saving the test image
    tiles = image_slicer.slice((resized_path + "/" + imageName + image_type),
                               split,
                               save=False)  #Slicing the test image up
    image_slicer.save_tiles(
        tiles, directory=sliced_path, prefix=imageName, format=image_type[1:]
    )  #Saving the sliced test images into the next folder

    for file in glob.glob(sliced_path + "/*" + image_type):

        img = cv2.imread(
            file,
            cv2.IMREAD_GRAYSCALE)  #Reading the sliced image into an array
        base_name = os.path.basename(
            os.path.normpath(file))  #Getting image names
        img = np.expand_dims(img, -1)  #Expanding dimensions
        img = np.expand_dims(img, 0)  #Expanding dimensions
        img = img / 255.0  #Normalising values

        predicted_image = segmentation_model.predict(
            img)  #Predicting the image
        predicted_image = predicted_image[
            0, :, :, 0]  #Removing the dimensions to (256,256)
        predicted_image = predicted_image > threshold  #Setting the threshold to filter out the noise ~ recommended is 0.99
        predicted_image = predicted_image * 255  #Reverse normalising to get exact shades of colour
        os.chdir(predicted_path)  #Changing directory for it to be saved
        cv2.imwrite(base_name, predicted_image)  #Saving predicted image

    newtiles = image_slicer.open_images_in(
        'D:/Project/FYP/Data For Gavin/Inserts/Results/.'
    )  #Opening image in tiled predicted images
    imageAll = image_slicer.join(newtiles)  #Joining the images together
    imageAll.save('D:/Project/FYP/Data For Gavin/Inserts/Results/' +
                  imageName + '.png')  #Saving the combined image together

    return imageName
Пример #13
0
def slice_jpeg(jpeg_img, num_slices, jpeg_slices_folder, slice_name):

    tiles = image_slicer.slice(
        jpeg_img, num_slices, save=False)
    image_slicer.save_tiles(tiles, directory=jpeg_slices_folder,
                            prefix=slice_name, format='jpeg')

    return
Пример #14
0
def _shatter(impath, savedir, k):
    im = Image.open(impath)
    basename = os.path.basename(impath)[:-4]
    try:
        tiles = image_slicer.slice(impath, k, save=False)
        image_slicer.save_tiles(tiles, directory=savedir, prefix=basename)
    except Exception as e:
        print(e)
Пример #15
0
def slice(number, IMAGE, location):
    '''
	called by startPredicting()
    slice image to (number param) slices and add to the slices folder (location param)
    name of each slice is the coordinates of the slice based on the IMAGE
    '''
    print("slicing...")
    tiles = image_slicer.slice(IMAGE, number, save=False)
    image_slicer.save_tiles(tiles, directory=location, prefix='slice')
Пример #16
0
def openCV(raw_img):
    link = "C:/Users/no1do/Desktop/daramg/"
    tiles = image_slicer.slice(str(link) + 'Rasp/' + raw_img, 4, save=False)
    image_slicer.save_tiles(tiles,
                            directory=str(link) + 'split/',
                            prefix=raw_img[:-4])
    s = os.path.splitext(raw_img)
    s = os.path.split(s[0])
    link = 'C:/Users/no1do/Desktop/daramg/split/'
    img_list = [
        str(link) + s[1] + '_01_01.png',
        str(link) + s[1] + '_01_02.png',
        str(link) + s[1] + '_02_01.png',
        str(link) + s[1] + '_02_02.png'
    ]
    # 경로값 수정
    result = []

    for i in img_list:
        img = cv2.imread(i)
        img = cv2.resize(img, None, fx=0.4, fy=0.4)
        height, width, channels = img.shape
        blob = cv2.dnn.blobFromImage(img,
                                     0.00392, (416, 416), (0, 0, 0),
                                     True,
                                     crop=False)
        net.setInput(blob)
        outs = net.forward(output_layers)

        class_ids = []
        confidences = []

        boxes = []
        for out in outs:
            for detection in out:
                scores = detection[5:]
                class_id = np.argmax(scores)
                confidence = scores[class_id]
                if confidence > 0.5:
                    # Object detected
                    center_x = int(detection[0] * width)
                    center_y = int(detection[1] * height)
                    w = int(detection[2] * width)
                    h = int(detection[3] * height)
                    # Rectangle coordinates
                    x = int(center_x - w / 2)
                    y = int(center_y - h / 2)
                    boxes.append([x, y, w, h])
                    confidences.append(float(confidence))
                    class_ids.append(class_id)

        if 0 in class_ids:
            result.append(1)
        else:
            result.append(0)
    return result
Пример #17
0
def slicing(img_path, save_path, no_of_slices):
    # slicing the binary mask images into 49 slices(7*7) using image_slicer
    tiles = image_slicer.slice(img_path, no_of_slices, save=False)
    # saving the sliced images of binary mask in the respective folders
    image_slicer.save_tiles(tiles,
                            directory=save_path,
                            prefix='slice',
                            format="jpeg")

    return tiles
Пример #18
0
def slice_img(path_img):
    # Variaveis
    qtd_slices = 64  #8x8

    #Criar o diretorio caso nao exista
    dir = cria_diretorio()

    # Dividir a imagem em 64 partes
    tiles = image_slicer.slice(path_img, qtd_slices, save=False)
    image_slicer.save_tiles(tiles, directory=dir, format='JPEG')
Пример #19
0
def slice_screenshot(screen):

    dim = 175
    y, x = 714, 15
    crop = screen[y:y+6*dim, x:x+6*dim]
    cv2.imwrite('board.png', crop)
    tiles = image_slicer.slice('board.png', 36, save=False)
    image_slicer.save_tiles(tiles, directory=PATH_SLICES)
    slices_dir = os.listdir(PATH_SLICES)

    return slices_dir
Пример #20
0
def slicer():
    directory_in_str = '/Users/travis.howe/Desktop/rc/vocab_images'

    for file in os.listdir(directory_in_str):
        tiles = image_slicer.slice('{0}/{1}'.format(directory_in_str, file),
                                   8,
                                   save=False)
        image_slicer.save_tiles(
            tiles,
            directory='{0}_sliced'.format(directory_in_str),
            prefix=file)
Пример #21
0
def sliceup():
    for picture in directory:
        newFolderName = os.path.splitext(picture)[0]
        folderpath = outpath + "/" + newFolderName
        inputpath = startpath + "/" + picture
        outputpath = folderpath
        tiles = image_slicer.slice(inputpath, 256, save=False)
        image_slicer.save_tiles(tiles,
                                directory=outputpath,
                                prefix='slice',
                                format='png')
Пример #22
0
def save_pictures(tiles, save_path):
    try:
        os.mkdir(save_path)
    except:
        print("Folder is already exists")
    save_path = "%s/" % save_path
    # print(save_path)

    image_slicer.save_tiles(tiles, directory=save_path, prefix='slice')

    return save_path
Пример #23
0
def split_images(images_folder, cls, num_splits):
    os.mkdir(os.path.join(images_folder, 'split_' + cls))
    for directory, subdirectories, files in os.walk(
            os.path.join(images_folder, cls)):
        for file in files:
            file_name = os.path.join(images_folder, cls, file)
            tiles = image_slicer.slice(file_name, int(num_splits), save=False)
            image_slicer.save_tiles(tiles,
                                    directory=os.path.join(
                                        images_folder, 'split_' + cls),
                                    prefix=get_basename(file_name))
Пример #24
0
def image_splitter(solved_jigsaw_image, unsolved_jigsaw_image, n_pieces, save=False):
    tiles = image_slicer.slice(solved_jigsaw_image, n_pieces, save=False)

    if save is True:
        new_directory = PATH + unsolved_jigsaw_image[:-4]

        if not os.path.exists(new_directory):
            os.mkdir(new_directory)

        image_slicer.save_tiles(tiles, directory=new_directory, prefix='slice', format='png')

    return tiles
Пример #25
0
def split_image_directory(directory, number_of_tiles, Package_dir):
    for dirpath, _, filenames in os.walk(directory):
        for f in filenames:
            abspath = os.path.abspath(os.path.join(dirpath, f))
            if f != ".DS_Store":
                tiles = image_slicer.slice(abspath,
                                           number_of_tiles,
                                           save=False)
                image_slicer.save_tiles(tiles,
                                        directory=Package_dir + "/tile_images",
                                        prefix=f.split('.')[0])
            print("image ", f, " processed")
Пример #26
0
def startCutting(startpath, outpath, gridoutpath, directory, outputs):
    for file in directory:
        if not file.startswith('.'):
            newFolderName = os.path.splitext(file)[0]
            folderpath = outpath + "/" + newFolderName
            inputpath = startpath + "/" + file
            outputpath = folderpath
            tiles = image_slicer.slice(inputpath, 1024, save=False)
            image_slicer.save_tiles(tiles,
                                    directory=outputpath,
                                    prefix='slice',
                                    format='png')
        print("cut")
Пример #27
0
def cut_frames(PATH_FRAMES, PATH_FRAMES_PIECES):
    """
    This function cuts a frame in 6
    """
    count = 0
    # nframe = 0
    for foto in glob.glob(PATH_FRAMES + "*.jpg"):
        frames = image_slicer.slice(foto, 6, save=False)
        image_slicer.save_tiles(frames,
                                directory=PATH_FRAMES_PIECES,
                                prefix='slice' + str(count))
        count += 1

    return True
Пример #28
0
def slice_img(indir_slicing, train_path, n_tiles, test_path, perc_test):
    '''
    Split images in n tiles. Default is 4. 
    Supports .png and .jpg files
    '''
    for root, dirs, filenames in os.walk(indir_slicing):
        for file in filenames:
            if file.endswith('.png') or file.endswith('.jpg'):
                tiles = image_slicer.slice(os.path.join(indir_slicing, file),
                                           n_tiles,
                                           save=False)
                image_slicer.save_tiles(tiles,
                                        directory=train_path,
                                        prefix=file)
Пример #29
0
def startCutting():
    for picture in directory:
        newFolderName = os.path.splitext(picture)[0]
        folderpath = outpath + "/" + newFolderName
        os.mkdir(folderpath)
        inputpath = startpath + "/" + picture
        outputpath = folderpath
        print(inputpath)
        print(outpath)
        tiles = image_slicer.slice(inputpath, 256, save=False)
        image_slicer.save_tiles(tiles,
                                directory=outputpath,
                                prefix='slice',
                                format='png')
    print("words")
Пример #30
0
def slice(path):
    clsLabels = np.array(['etyn', 'etym', 'etyo'])
    import glob
    for i in range(0, len(clsLabels)):
        filesCls = glob.glob(path + '/*/*' + clsLabels[i] + ".jpg")
        for k in range(0, len(filesCls)):
            tiles = image_slicer.slice(filesCls[k], 25, save=False)
            image_slicer.save_tiles(
                tiles,
                directory=r'C:\Users\covac\Desktop\img\All_tiles_in1',
                prefix=filesCls[k],
                format='jpeg')
            import shutil
            shutil.move(
                filesCls[k], r'C:\Users\covac\Desktop\img\All_pics_1' +
                os.path.basename(filesCls[k]))
Пример #31
0
def SplitImage(img, N):
    #creates tiles from image given
    #image is split into equally sized tiles
    tiles = image_slicer.slice(img, N, save=False)
    #saves files in directory
    image_slicer.save_tiles(tiles, directory=mypath, prefix='slices')
    #stores a list of sorted tiles in variable 'onlyfiles' with file extension '.png'
    tile_img = [
        f for f in listdir(mypath) if isfile(join(mypath, f))
        if f.startswith('slices') if f.endswith(".png")
    ]
    tile_img.sort()
    rgbtiles = most_frequent_color(tile_img)
    rgbimg = ResizeImg(tile_img[0])
    # a list of tuples containging rgb values are stored in variable 'rgbimg'
    #returns a list of rgb values in tuples
    return rgbtiles, rgbimg
Пример #32
0
    def slice_folder(self, input_path):
        """
        This function should be called with a path to a folder as argument. It will
        extract images from the folder with NO recursivity and will slice them if the
        weight is > to the height.
            :param input_path: path/to/folder/bigImage.jpg
            output = path/to/folder_sliced/bigImage-0_01_01.jpg
                     path/to/folder_sliced/bigImage-0_01_02.jpg

        """
        print("Parsing folder: " + input_path)
        if input_path[-1] == self.sep:
            path_out = input_path[:-1] + suffix_sliced
        else:
            path_out = input_path + suffix_sliced
        try:
            os.mkdir(path_out)
        except OSError:
            pass
        for files in sorted(os.listdir(input_path)):
            ext = files[-3:].lower()
            if ext in images:
                file_to_add = os.path.join(input_path, files)
                im = Image.open(file_to_add)
                (w, h) = im.size
                if w > h:
                    if self.verbose:  # Note: If verbose
                        print("        Slicing ", file_to_add, str(w) + "x" + str(h))
                    tiles = image_slicer.slice(file_to_add, 2, save=False)
                    size_tile = len(tiles)
                    if self.reverse:  # If it's a manga, then the first page is the right page
                        for a in tiles:
                            pos_tile = a.position
                            a.position = (size_tile, pos_tile[1])
                            size_tile -= 1
                    image_slicer.save_tiles(tiles, directory=path_out, prefix=files[:-4], format='jpg')
                else:
                    shutil.copy(file_to_add, path_out)
        return path_out
     sample_size = int(round( len(slicedf) * 0.01 ))
     slicedf = slicedf.sample(n=sample_size)
     idxlist = list(slicedf.sliceidx.unique())
     
     tmp = tmp.loc[idxlist,:]
     for u in tmp.index:
         path = tmp.local_path.loc[u]
         slices = list(slicedf.slicenum[slicedf.sliceidx==u])
         nslice = tmp.nslice.loc[u]
 
         try:
             
             tiles = image_slicer.slice(path,nslice,save=False)
             tile_subset = tuple(tiles[v] for v in slices)
             image_slicer.save_tiles(tile_subset,
                                 directory=SLICEDIR,
                                 prefix=str(u))
                                 
         except Exception as e:
             print(e)
         
         print(i,yr,"slice",u,"of",len(tmp))
 
     actslicedf = pd.DataFrame()
     actslice_paths = glob.glob(os.path.join(SLICEDIR,"*.png"))
     actslicedf['local_path'] = [item for item in actslice_paths]
     actslicedf['basename'] = actslicedf.local_path.apply(os.path.basename)
     actslicedf['idx'] = [int(item.split("_")[0]) for item in actslicedf.basename]
     tmp = tmp[['secpast']]
     tmp['idx'] = tmp.index
     tmp.set_index("idx",inplace=True)
Пример #34
0
infile = "/data/damoncrockett/downtown_SD_Flickr/data/all_image_exists.csv"
num_slices = 2048

df = pd.read_csv(infile)
df = df.sample(n=16384)

# Okay this is hacky...I don't care. Science awaits.
BASE_DIR = "/data/damoncrockett/downtown_SD_Flickr/images_sliced_"

counter=-1
for file in df.local_folder:
    counter +=1
    print counter
    try:
        tiles = image_slicer.slice(file,num_slices,save=False)
        if counter > 12000:
            ext = "4/"
        elif counter > 8000:
            ext = "3/"
        elif counter > 4000:
            ext = "2/"
        else:
            ext = "1/" 
            
        image_slicer.save_tiles(tiles,
                                directory=BASE_DIR+ext,
                                prefix=str(counter))
    except:
        print 'err'
Пример #35
0
import image_slicer
from PIL import Image
from PIL import ImageDraw, ImageFont

play = 0
score = 4

while play == 0: 

    tiles = image_slicer.slice(input('Enter File Name:'), 4, save=False)

    for tile in tiles:
        overlay = ImageDraw.Draw(tile.image)

    image_slicer.save_tiles(tiles)

    image1 = Image.open('C:\\Users\\Michael\\Documents\\205Project2\\Project2\\_02_02.png')
    image2 = Image.open('C:\\Users\\Michael\\Documents\\205Project2\\Project2\\_02_01.png')
    image3 = Image.open('C:\\Users\\Michael\\Documents\\205Project2\\Project2\\_01_02.png')
    image4 = Image.open('C:\\Users\\Michael\\Documents\\205Project2\\Project2\\_01_01.png')

    width,height = image1.size
    width = (width * 2) + 20
    height = (height * 2) + 20  
    jigsaw = Image.new('RGB',(width,height))
    width,height = image1.size
    jigsaw.paste(image1,(0,0))
    jigsaw.paste(image2,(width + 10,0))
    jigsaw.paste(image3,(0,height + 10))
    jigsaw.paste(image4,(width + 10, height + 10))
Пример #36
0
import image_slicer
import pandas as pd
import os
import sys

infile = sys.argv[1]
num_slices = int(sys.argv[2])
target = sys.argv[3]

df = pd.read_csv(infile)

# option to sample
df = df.sample(n=360)
df.reset_index(drop=True,inplace=True)

n = len(df.index)
for i in range(n):
    try:
        file = df.filename.loc[i]
        tiles = image_slicer.slice(file,num_slices,save=False)
        image_slicer.save_tiles(tiles,directory=target,prefix=os.path.basename(file))
        print i
    except:
        print 'err'
Пример #37
0
TILEPATH = './static/images/tiles/'
TARGETFILE = 'brain.png'
NTILES = 16

# first delete all the files in the static/images/tiles folder
files = os.listdir(TILEPATH)
for myfile in files:
	if myfile != 'placeholder.txt':
		print "removing existing file", TILEPATH+myfile
		os.remove(TILEPATH+myfile)

# query existing pixels
Pixels.query.delete()

# create the tiles using the target image
tiles = image_slicer.slice(TARGETFILE, NTILES, save=False)
image_slicer.save_tiles(tiles, prefix='tile', directory='static/images/tiles', format='png')

# add tiles to database
for tile in tiles:
	pixel_width, pixel_height = tile.image.size
	print "dimensions:", (pixel_width, pixel_height) , "filename:", tile.filename
	pixel_attributes = dict(filename = tile.filename,
								n_completed = 0,
								width = pixel_width,
								height = pixel_height)
	pixel = Pixels(**pixel_attributes)
	db_session.add(pixel)
	db_session.commit()

Пример #38
0
import image_slicer
import glob
import os
import sys

input_file = "/Users/damoncrockett/Desktop/encanto_4096.tif"
num_slices = float(sys.argv[1])
target = "/Users/damoncrockett/Desktop/enc/slices/"

# don't need informative filenames at this stage
tiles = image_slicer.slice(input_file,num_slices,save=False)
image_slicer.save_tiles(tiles,directory=target)

new_target = "/Users/damoncrockett/Desktop/enc/slices_of_slices/"
# can adjust num_slices if need be                      
counter=-1
for file in glob.glob(os.path.join(target,'*.png')):
    counter +=1
    print counter
    try:
        tiles = image_slicer.slice(file,num_slices,save=False)
        image_slicer.save_tiles(tiles,
                            directory=new_target,
                            prefix=str(counter))
    except:
        print 'err'