Exemplo n.º 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)
Exemplo n.º 2
0
def upload_file():
    if request.method == 'POST':

        a = ""

        print(request.files)
        if 'file_idproof' not in request.files:
            message = "no file found"
            return json.dumps({"message": message, "dob": a})
        file = request.files['file_idproof']
        file.save("a.jpg")

        text = []
        image_slicer.slice("a.jpg", 10)

        for f in os.listdir("."):
            if '.png' in f:
                image = Image.open(f)
                t = pytesseract.image_to_string(image, lang='eng')
                text.append(t)

        for i in range(len(text)):
            try:
                match = re.search(r'(\d+/\d+/\d+)', text[i]).group(1)
                a = match
            except:
                pass

        if a == "":
            message = "id upload failed"
        else:
            message = "id uploded successfully"
        return json.dumps({"message": message, "dob": a})
Exemplo n.º 3
0
def split():
    for item in dirs:
        if os.path.isfile(path + item):
            image_slicer.slice(
                path + item, 12
            )  # instead of 12, specify this number for grids i.e. number of slices
            print("Done with Slicing...!!!")
Exemplo n.º 4
0
def cut_images(path):
    print(img_path)
    for fn in glob.glob(img_path + '/*.png'):
        try:
            img = Image.open(fn, 'r')
        except IOError:
            print("Image at specified path not found.")
            sys.exit()

        width, height = img.size   # Get dimensions
        left = (width - height) / 2
        right = (width + height) / 2

        # if image is less than 1944 in height, resize
        base_height = 1944
        if height is not base_height:
            hpercent = (base_height / float(height))
            new_width = (float(width) * float(hpercent))
            img = img.resize((new_width, base_height), Image.ANTIALIAS)

        img = img.crop((left, 0, right, base_height))

        new_img_path = 'processed_8x8/' + fn.split('/')[1]
        print(new_img_path)
        img.save(new_img_path, 'PNG')

        num_slices = 64
        image_slicer.slice(new_img_path, num_slices)
Exemplo n.º 5
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')
Exemplo n.º 6
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 "============================"
Exemplo n.º 7
0
def main():
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "--image",
        type=str,
        default='',
        required=True,
        help="Your Image path",
    )

    parser.add_argument(
        "--slicer",
        type=int,
        default='',
        required=True,
        help="Your slicer value (es. 8x8 = value --> 64)",
    )

    if len(sys.argv[1:]) == 0:
        parser.print_help()
        parser.exit()

    args = parser.parse_args()
    image_slicer.slice(args.image, args.slicer)
Exemplo n.º 8
0
def slice_image(fn):
    try:
        img = Image.open(fn, 'r')
    except IOError:
        print("Image at specified path not found.")
        sys.exit()

    width, height = img.size  # Get dimensions
    left = (width - height) / 2
    right = (width + height) / 2

    # if image is less than 1944 in height, resize
    base_height = 1944
    if height is not base_height:
        hpercent = (base_height / float(height))
        new_width = (float(width) * float(hpercent))
        img = img.resize((new_width, base_height), Image.ANTIALIAS)

    img = img.crop((left, 0, right, base_height))

    fn_split = fn.split('/')

    if not os.path.exists(BASE_TEMP_PATH):
        os.makedirs(BASE_TEMP_PATH)

    new_img_path = BASE_TEMP_PATH + fn_split[len(fn_split) - 1]
    print(new_img_path)
    img.save(new_img_path, 'PNG')

    num_slices = 64
    image_slicer.slice(new_img_path, num_slices)

    os.remove(new_img_path)
Exemplo n.º 9
0
def evaluateFace(filenames, answers):
    clrs = ['B', 'R', 'G', 'O', 'W', 'Y']
    results = []
    for filename in filenames:
        image_slicer.slice(filename, 9)
        extens = ".jpg"
        prefix = filename.replace(extens, "")
        clrCounts = [0, 0, 0, 0, 0, 0]

        for row in range(1, 4):
            for col in range(1, 4):
                curr_file = prefix + "_0" + str(row) + "_0" + str(col) + ".png"

                print([row, col])
                img = io.imread(curr_file)
                rows, cols, rgb = img.shape
                img_crop = img[round(rows / 4):round(rows * 3 / 4),
                               round(cols / 4):round(cols * 3 / 4)]
                img_lab = color.rgb2lab(img_crop)

                max_rows, max_cols, lab = img_lab.shape

                measure_int = 5
                curr_int = 0
                for pix_row in range(max_rows):
                    for pix_col in range(max_cols):

                        if (curr_int == measure_int):
                            currPix = img_lab[pix_row, pix_col, :]
                            currPix = np.asarray([currPix])
                            currPix = currPix - ScMean
                            currPix = currPix / ScStd

                            choice = mlMod.predict(currPix)
                            clrCounts[choice - 1] = clrCounts[choice - 1] + 1
                            curr_int = 0
                        else:
                            curr_int = curr_int + 1

                ind = np.argmax(clrCounts)
                results.append(clrs[ind])
                clrCounts = [0, 0, 0, 0, 0, 0]

    if (len(answers) != len(results)):
        print('Error: Not enough classifications generated.')

    else:
        correct = 0
        wrong = []
        for index in range(len(answers)):
            if (answers[index] == results[index]):
                correct = correct + 1
            else:
                wrong.append([results[index], answers[index], index])
    print(wrong)
    return (correct / len(answers))
Exemplo n.º 10
0
def home():

    name = 'ttt.jpeg'
    nm = name.split(".")
    image = cv2.imread(name)

    image_slicer.slice(name, 4)
    slice_1 = nm[0] + '_01_01.png'
    slice_2 = nm[0] + '_01_02.png'
    slice_3 = nm[0] + '_02_01.png'
    slice_4 = nm[0] + '_02_02.png'
    lst = []

    i1 = cv2.imread(slice_1)

    from pyzbar.pyzbar import decode

    barcodes = pyzbar.decode(i1)
    obj = barcodes
    for barcode in obj:
        print(barcode.data)
        b1 = barcode.data
        lst.append(b1)

    i2 = cv2.imread(slice_2)

    barcodes = pyzbar.decode(i2)
    obj = barcodes
    for barcode in obj:
        print(barcode.data)
        b2 = barcode.data
        lst.append(b2)

    i3 = cv2.imread(slice_3)

    barcodes = pyzbar.decode(i3)
    obj = barcodes
    for barcode in obj:
        print(barcode.data)
        b3 = barcode.data
        lst.append(b3)

    i4 = cv2.imread(slice_4)

    barcodes = pyzbar.decode(i4)
    obj = barcodes
    for barcode in obj:
        print(barcode.data)
        b4 = barcode.data
        lst.append(b4)

    if (request.method == 'GET'):
        list = []
        for data in lst:
            list.append(data.decode("utf-8"))
        return jsonify({'barcode': list})
Exemplo n.º 11
0
def framer(main_path, name, label, training=True):

    if training:
        directory = '/home/alon/Documents/train_directory/label_'
        print('Processing training images.')
    else:
        directory = '/home/alon/Documents/validation_directory/label_'
        print('Processing validation images.')

    i = 0
    x = 10  # i actually don't know why this is necessary
    cd = main_path + name
    for _ in os.listdir(cd):
        if _ != 'ready':
            try:
                img = Image.open(cd + '/' + _)

                old_size = img.size
                new_size = (128, 128 + x)
                img = img.crop((0, 0, old_size[0], old_size[1] - x))

                deltaw = int(new_size[0] - old_size[0])
                deltah = int(new_size[1] - old_size[1])
                ltrb_border = (int(deltaw / 2), int(deltah / 2),
                               int(deltaw / 2), int(deltah / 2))
                img_with_border = ImageOps.expand(img,
                                                  border=ltrb_border,
                                                  fill='black')

                # img_with_border.save('Blueberry/ready/' + str(i) + '.png'
                img_with_border = img_with_border.resize(size=(128, 128))
                for theta in range(0, 360, 45):
                    img_with_border.rotate(theta).save(directory + str(label) +
                                                       '/' + str(i) + '.png')
                    slicer.slice(
                        directory + str(label) + '/' + str(i) + '.png', 4)
                    os.remove(directory + str(label) + '/' + str(i) + '.png')
                    i = i + 1
                if i > 3:
                    im = Image.open(directory + '0/0_01_01.png')
                    sys.stdout.write("\r" + str(i) + ' ' + name +
                                     ' images processed.' + str(im.size))

                sys.stdout.write("\r" + str(i) + ' ' + name +
                                 ' images processed.')
                sys.stdout.flush()

            except Exception:
                print('theres an issue')
                raise

    sys.stdout.write("\r" + 'A total of ' + str(i) + ' ' + name +
                     ' images have been processed.')
    sys.stdout.flush()
Exemplo n.º 12
0
def get_slices(image_path):
    image_slicer.slice(image_path, 9)
    slices = []
    row = []
    for i in range(3):
        for j in range(3):
            slice_path = '.' + image_path.split('.')[1] + '_0' + str(
                i + 1) + '_0' + str(j + 1) + '.png'
            slices.append(ocv.imread(slice_path))
            os.remove(slice_path)
    return slices
Exemplo n.º 13
0
def perform(original_image_path, changed_image_path):
    original_image = Image.open(original_image_path)
    changed_image = Image.open(changed_image_path)
    w, h = original_image.size
    tile_size = 64
    hash_length = 64
    threshold = hash_length * 0.15
    column, row = count_tiles_size(w, h, tile_size)

    # Slice image to 64x64 blocks
    original_tiles = image_slicer.slice(original_image_path,
                                        number_tiles=column * row,
                                        col=column,
                                        row=row,
                                        save=False)
    changed_tiles = image_slicer.slice(changed_image_path,
                                       number_tiles=column * row,
                                       col=column,
                                       row=row,
                                       save=False)

    # Итеративно проходим по каждому блоку изображения
    for original_tile, changed_tile in zip(original_tiles, changed_tiles):
        # Получаем хеш блока
        original_hash = imagehash.phash_simple(original_tile.image)
        changed_hash = imagehash.phash_simple(changed_tile.image)

        # Прям хеш методом наименее значащего бита
        original_tile.image = lsb.hide(original_tile.image, str(original_hash))
        changed_tile.image = lsb.hide(changed_tile.image, str(changed_hash))

        # Забираем хеш из изображения
        decoded_original_hash = lsb.reveal(original_tile.image.copy())
        decoded_changed_hash = lsb.reveal(changed_tile.image.copy())

        # Вычисляем расстояние Хемминга и сравниваем его с пороговой границей
        if hamming_distance(decoded_original_hash,
                            decoded_changed_hash) > threshold:
            # Закрашиваем измененные области
            # The current version supports all possible conversions between “L”, “RGB” and “CMYK.” The matrix argument only supports “L” and “RGB”.
            rgb2xyz = (0.412453, 0.357580, 0.180423, 0, 0.212671, 0.215160,
                       0.072169, 0, 0.019334, 0.919193, 0.950227, 0)
            changed_tile.image = changed_tile.image.convert("RGB", rgb2xyz)

    result_image = image_slicer.join(changed_tiles, w, h)
    file_name = original_image_path.split(".")[-2]
    result_image_path = original_image_path.replace(file_name,
                                                    file_name + "_result")
    result_image.save(result_image_path)

    original_image.show()
    changed_image.show()
    result_image.show()
Exemplo n.º 14
0
 def main(self):
     self.sudoku = self.boardFinder()
     if self.sudoku is not None:
         self.squares = self.square()
         self.img = cv2.imread('images/sudokubrd_cap.png')
         self.grayimg = self.canny()
         self.cpImg = self.canny.copy()
         self.colorConvImg = cv2.cvtColor(self.img, cv2.COLOR_RGB2BGR)
         cv2.imwrite('images/sudokubrd_canny.png', self.grayimg)
         slice('images/sudokubrd_canny.png', 9*9,)
         self.numlist = self.numDetector()
         solver.solver(self.numlist)
Exemplo n.º 15
0
def read_extra(extradata_path, img_size):
    train_ids = next(
        os.walk(extradata_path))[2]  #Generates all file anmes in the tree
    masks = [train_id for train_id in train_ids if re.search('mask', train_id)]
    masks.sort()
    images = [
        train_id for train_id in train_ids if re.search('original', train_id)
    ]
    images.sort()

    #initialize storage for the data
    X_extra = np.zeros((len(train_ids), img_size, img_size, 3), dtype=np.uint8)
    Y_extra = np.zeros((len(train_ids), img_size, img_size, 1), dtype=np.bool)

    temp = np.zeros((1, img_size, img_size, 3), dtype=np.uint8)
    temp_mask = np.zeros((1, img_size, img_size, 1), dtype=np.bool)
    temp_contour = np.zeros((1, img_size, img_size, 1), dtype=np.bool)
    for i, id_ in enumerate(masks):
        maskid = masks[i]
        imageid = images[i]
        contourid = contours[i]
        img = cv2.imread(extradata_path + '/' + imageid)
        mask = cv2.imread(extradata_path + '/' + maskid, 0)
        if img.shape[0] > 512:
            tiles = image_slicer.slice(extradata_path + '/' + imageid,
                                       16,
                                       save=False)
            tiles_mask = image_slicer.slice(extradata_path + '/' + maskid,
                                            16,
                                            save=False)
            X_extra[i] = cv2.resize(np.array(tiles[0].image),
                                    (img_size, img_size))
            Y_extra[i, ..., 0] = cv2.resize(
                np.array(tiles_mask[0].image, dtype=np.uint8),
                (img_size, img_size))
            for counter, (tile, tile_mask) in enumerate(zip(tiles,
                                                            tiles_mask)):
                if (counter > 0):
                    temp[0, ...] = cv2.resize(np.array(tile.image),
                                              (img_size, img_size))
                    temp_mask[0, ..., 0] = cv2.resize(
                        np.array(tile_mask.image, dtype=np.uint8),
                        (img_size, img_size))
                    X_extra = np.concatenate([X_extra, temp], axis=0)
                    Y_extra = np.concatenate([Y_extra, np.array(temp_mask)])
        else:
            img = cv2.resize(img, (img_size, img_size))
            mask = cv2.resize(mask, (img_size, img_size))
            X_extra[i] = img
            Y_extra[i] = mask[:, :, 0:1]
    return X_extra, Y_extra
Exemplo n.º 16
0
Arquivo: app.py Projeto: redcrix/pyapi
def upload_file():
	if request.method == 'POST':
		a = ""
		value=0
		text=[]
		if 'aid' not in request.files:
			message="no file found"
			value=404
			return json.dumps({"code":value,"message":message})
		file = request.files['aid']
		idtype = str(request.form['idtype'])
		file.save("a.jpg")
		for f in os.listdir("/home/redcrix/mysite/static/"):
		    os.remove("/home/redcrix/mysite/static/"+f)
		time = datetime.now().strftime("%d-%b-%Y_%H:%M:%S")
		shutil.copy("a.jpg", "/home/redcrix/mysite/static/"+time+".jpg")
		idpic=str("http://redcrix.pythonanywhere.com/static/"+time+".jpg")
		image = Image.open("a.jpg")
		t = pytesseract.image_to_string(image, lang='eng')
		text.append(t)
		for i in text:
			try:
				match = re.search(r'(\d+/\d+/\d+)', i).group(1)
				a = match
			except:
				pass

		if a=="":

		    image_slicer.slice("a.jpg", 10)
		    for f in os.listdir("."):
    			if '.png' in f:
    				image = Image.open(f)
    				t = pytesseract.image_to_string(image, lang='eng')
    				text.append(t)

		for i in text:
			try:
				match = re.search(r'(\d+/\d+/\d+)', i).group(1)
				a = match
			except:
				pass


		if a=="":
			message="id upload failed"
			value=201
		else:
			message="id uploded successfully"
			value=202
		return json.dumps({"text":text,"code":value,"img": idpic, "message":message,"dob": a})
Exemplo n.º 17
0
def Puzzle_RandomShuffle(path, n, seed):
    # """
    # @input  path:  image path
    # 		n:		number of tiles/puzzles
    # 		seed:	seed for Random
    # @return randomly shuffled puzzle image
    # """

    c = []
    i = 0

    # Read image
    #cv2_imshow(img)

    # split image into n tiles
    tiles = image_slicer.slice(path, n, save=False)
    #plot puzzle
    #plt.imshow(np.asarray(tiles[0].image))

    # Shuffle tiles
    random_index = np.arange(n)
    np.random.shuffle(random_index)

    # Collect oordinates for each tile
    for tile in tiles:
        c.append(tile.coords)

    # Re-assign coords
    for tile in tiles:
        tile.coords = c[random_index[i]]
        i = i + 1
        #print(tile.coords)

    return image_slicer.join(tiles)
Exemplo n.º 18
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:])
Exemplo n.º 19
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)
Exemplo n.º 20
0
def main(img_path):
    """ Here we split the sudoku grid into 81 cells after performing all the below preprocessing methods. """

    image, gray, thresh, contours = imageProcessor(img_path)
    best_cnt = bestContours(image, contours)
    image,out = maskCreator(gray, best_cnt, image, contours)
    gray = boxFinder(image, out)
    
    squares = infer_grid(gray)
    image = display_rects(gray, squares)
    image1 = Image.fromarray(image)
    image1.save('my.png')
    a = image_slicer.slice('my.png', 81)

    if 'temp' in os.listdir():
        shutil.rmtree('temp')
    os.mkdir('temp')
    for i,img in enumerate(sorted([file for file in os.listdir() if 'my_' in file])):
        src, dst = os.path.join(root, img), os.path.join(root, 'temp')
        shutil.move(src, dst)

    for img_name in os.listdir('temp'):
        if '.png' in img_name:
            img = cv2.imread(os.path.join(root, 'temp', img_name))
            img[img > 60] = 255
            cv2.imwrite(os.path.join(root, 'temp', img_name), img)
Exemplo n.º 21
0
def createMosaic(tim0, numTiles0, tree0, db0):
    tim = tim0
    numTiles = numTiles0
    kdTree = tree0
    db = db0

    # slice tim into tiles
    print "  Slicing " + tim + " into " + str(numTiles) + " tiles..."
    tiles = image_slicer.slice(tim, numTiles, save=False)

    # Replace slices with nearest neighbors from library
    print "  Replacing tiles with nearest neighbors..."
    for tile in tiles:
        tileRGB, tileColor = getDomIMAGEColor(tile.image)
        neighborDist, neighborIndex = kdTree.query(tileRGB)
        neighborFile = PREFIX + str(neighborIndex + 1) + SUFFIX
        iNbor = Image.open(neighborFile)
        # print tile.image.size
        iNbor = iNbor.resize(tile.image.size)
        tile.image.paste(iNbor)

    print "  Joining new tiles..."
    # image_slicer.save_tiles(tiles, prefix=tim[:-4])
    newMosaic = image_slicer.join(tiles)

    # Save the new image under the old filename appended with "_mosaic" and
    # the number of tiles, e.g. 'image_mosaic2000.jpg'
    newName = tim[:-4] + "_mosaic" + str(numTiles) + SUFFIX
    print "  Saving new mosaic under " + newName
    newMosaic.save(newName)

    return newMosaic
Exemplo n.º 22
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')
Exemplo n.º 23
0
def sliceAndEmbed(frames, secret_img_path, occ):
	''' Partitions secret image into smaller images and embeds them in cover video '''
	secret_img = Image.open(secret_img_path)
	frame_h, frame_w = frames[0].shape[:2]
	secret_h, secret_w = secret_img.size[1], secret_img.size[0]
	# Temporarily(& Arbritrarily) setting max slice size as 1 sixth of cover image
	max_h, max_w = frame_h/6, frame_w/6
	numberOfSlices = ceil(secret_h/max_h)*ceil(secret_w/max_w)
	tiles = image_slicer.slice(secret_img_path, numberOfSlices, save=False)

	# Rough Index data for now
	indexData = str(secret_img.size[0]) + ";" + str(secret_img.size[1]) + ";" 
	indexData+= str(len(tiles)) + ";" + str(tiles[0].image.size[0]) + ';' + str(tiles[0].image.size[1]) + '.'
	index = multi_text_sender.generateRandomFrameNo(len(frames), occ)
	for i in tiles:
		loc = multi_text_sender.generateRandomFrameNo(len(frames), occ)
		indexData += str(loc) + '.'
		cover_img = Image.fromarray(frames[loc])
		temp = ioi.hide_image(cover_img, i.image)
		frames[loc] = np.array(temp)

	# Index
	cover_img = Image.fromarray(frames[index])
	temp = ioi.hide_image(cover_img, i.image)
	frames[index] = np.array(temp)
	return frames
Exemplo n.º 24
0
def makeTiles():
    global rootTargetDirectory, zoomLevels, baseFactor

    for zl in range(1, zoomLevels):

        rows = baseFactor
        columns = baseFactor
        slices = rows * columns

        print("Processing - Zoom Level:" + str(zl) + " Slices:" + str(slices) +
              " Columns:" + str(columns) + " Rows:" + str(rows))

        tiles = image_slicer.slice(inputMap, slices, columns, rows, False)
        zlTargetDirectory = "tiles/" + str(zl)

        #make zoomlevel directory if not exists
        if not os.path.exists(zlTargetDirectory):
            os.makedirs(zlTargetDirectory)

        for tile in tiles:
            currentTargetDirectory = rootTargetDirectory + "/" + str(
                zl) + "/" + str(tile.row - 1)
            if not os.path.exists(currentTargetDirectory):
                os.makedirs(currentTargetDirectory)

            tileFilename = str(tile.column - 1) + ".png"
            #print(currentTargetDirectory+"/"+tileFilename)

            tile.save(filename=currentTargetDirectory + "/" + tileFilename)
            scaleTile(currentTargetDirectory + "/" + tileFilename)

        baseFactor = baseFactor * 2
Exemplo n.º 25
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')
Exemplo n.º 26
0
 def new(self):
     self.allSprites = pg.sprite.Group()
     self.imageTiles = pg.sprite.Group()
     self.lastPiece = pg.sprite.Group()
     self.mouse = pg.sprite.Group()
     self.moveGroup = pg.sprite.Group()
     temporList = []
     self.doggoPieces = slicer.slice("img/doggo.png", 20)
     for i in range(4):
         for x in range(5):
             y = ImageTile(self, IMAGEWIDTH * i, IMAGEHEIGHT * x)
             temporList.append(y)
     temporList[-1].kill()
     self.allSprites.remove(temporList[-1])
     self.lastPiece.add(temporList[-1])
     self.pointer = Pointer(self, self.mousePos)
     self.topWall = Wall()
     self.imageTiles.add(self.topWall)
     self.topWall.rect.bottom = 0
     self.topWall.rect.centerx = WIDTH / 2
     self.rightWall = Wall()
     self.imageTiles.add(self.rightWall)
     self.rightWall.rect.left = WIDTH
     self.rightWall.rect.centery = HEIGHT / 2
     self.leftWall = Wall()
     self.imageTiles.add(self.leftWall)
     self.leftWall.rect.right = 0
     self.leftWall.rect.centery = HEIGHT / 2
     self.bottomWall = Wall()
     self.imageTiles.add(self.bottomWall)
     self.bottomWall.rect.top = HEIGHT
     self.bottomWall.rect.centerx = WIDTH / 2
Exemplo n.º 27
0
def main():
    try:
        img_path = sys.argv[1]
    except IndexError:
        print('Please provide image path!')
        return
    if os.path.isfile(img_path):
        with Image.open(img_path) as img:
            print(img.size)
            square_image = get_square_image(img)
            _, file_extension = os.path.splitext(img_path)
            filename = os.path.basename(img_path)
            output_uri = os.path.join(
                os.path.dirname(img_path), '{}_square.{}'.format(
                    filename,
                    file_extension
                )
            )
            imageio.imwrite(output_uri, square_image)

            # slice the image
            slices = image_slicer.slice(output_uri, 2, save=False)
            for index, s in enumerate(slices):
                image = s.image
                image = image.convert('RGB')
                output_uri = os.path.join(
                    os.path.dirname(img_path), 'slice_{}.{}'.format(
                        index,
                        file_extension
                    )
                )
                #convert image to numpy array then save to file
                imageio.imwrite(output_uri, numpy.asarray(image))
    else:
        print('File not found!')
Exemplo n.º 28
0
def avg_val_pic(img, numtiles, reshape_x,
                reshape_y):  #input your img as file path
    from skimage import img_as_float
    import numpy as np
    import matplotlib.pyplot as plt
    import image_slicer
    from PIL import Image
    from skimage.filters import sobel

    imag = Image.open(img)
    image = sobel(img_as_float(imag))  # Applies Sobel filter to image
    tiles = image_slicer.slice(img, numtiles,
                               save=False)  # Tiles the images into numtiles
    strg_arr = np.zeros((numtiles), dtype=np.uint16)  # storage array of zeros

    for f, tile in enumerate(tiles):
        tl_img = tile.image
        pixels = (np.sum(tl_img))  # take sum pix value from sliced images
        strg_arr[
            f] = pixels  # sets all values in empty array to mean of the tile

    strg_arr = strg_arr.reshape(np.sqrt(numtiles),
                                np.sqrt(numtiles))  #reshape_x, reshape_y)
    plt.imshow(strg_arr,
               origin='lower',
               vmin=strg_arr.std(),
               vmax=strg_arr.max())
    plt.show()
Exemplo n.º 29
0
def createMosaic( tim0, numTiles0, tree0, db0 ):
	tim = tim0
	numTiles = numTiles0
	kdTree = tree0
	db = db0

	# slice tim into tiles
	print "  Slicing " + tim + " into " + str(numTiles) + " tiles..."
	tiles = image_slicer.slice(tim, numTiles, save=False)

	# Replace slices with nearest neighbors from library
	print "  Replacing tiles with nearest neighbors..."
	for tile in tiles:
		tileRGB, tileColor = getDomIMAGEColor(tile.image)
		neighborDist, neighborIndex = kdTree.query(tileRGB)
		neighborFile = PREFIX + str(neighborIndex + 1) + SUFFIX
		iNbor = Image.open(neighborFile)
		# print tile.image.size
		iNbor = iNbor.resize(tile.image.size)
		tile.image.paste(iNbor)
	
	print "  Joining new tiles..."
	# image_slicer.save_tiles(tiles, prefix=tim[:-4])
	newMosaic = image_slicer.join(tiles)

	# Save the new image under the old filename appended with "_mosaic" and 
	# the number of tiles, e.g. 'image_mosaic2000.jpg'
	newName = tim[:-4] + "_mosaic" + str(numTiles) + SUFFIX
	print "  Saving new mosaic under " + newName
	newMosaic.save(newName)

	return newMosaic
Exemplo n.º 30
0
def output(model):
    output_dir = 'test_images'
    img_name = 'PL13_C04_S2_C2_ch00.tif'
    img = os.path.join(output_dir, img_name)
    num_tiles = 16
    tiles = image_slicer.slice(img, num_tiles, save=True)

    for i in range(0, num_tiles):
        img = tiles[i].image

        img_asnp = np.asarray(img)
        img_astensor = torch.from_numpy(img_asnp).float()
        img_astensor = img_astensor.unsqueeze(0)
        img_astensor = img_astensor.permute(0, 3, 1, 2)
        out = model(img_astensor)
        out = out.squeeze(0)
        out = out.permute(1, 2, 0)
        print(out.shape)
        print(img_astensor)
        print(out)
        out_asnp = out.detach().numpy()
        print(np.shape(out_asnp))
        print(tiles[i].filename)
        imgout = Image.fromarray((out_asnp * 255).astype(np.uint8))
        imgout.save(tiles[i].filename[0:-4] + 'Out' + '.png')
        tiles[i].image = out_asnp
        # tile.image = Image.open(tile.filename)

    imageOutput = join(tiles)
    imageOutput.save('Out' + img_name)
Exemplo n.º 31
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)
Exemplo n.º 32
0
def put_image(name, *args, **kwargs):

    counter = Counter.objects.all()[0]
    if not counter:
        counter = Counter.objects.create(num=0)
    if counter.num > 133:
        counter.num = 0
    counter.num += 1
    counter.save()

    path_to_image = os.path.join(BASE_DIR,
                                 f'imagetask/images/data{counter.num}.png')
    tiles = image_slicer.slice(path_to_image, 100, save=False)
    i = 0
    for tile in tiles:
        i += 1
        with io.BytesIO() as data:
            # filename = tile.generate_filename(path=False)
            tile.save(data)
            data.seek(0, 0)
            readed_data = data.read()
            base_data = base64.b64encode(readed_data)
            img, created = Image.objects.get_or_create(name=i)
            img.data = base_data
            img.save()

    print(f'Image {counter.num} stored to DB by {name}')
Exemplo n.º 33
0
    def imageDivide(self, name, no):
        """
		Slice the image into multiple parts
		:param name: Path to the image
		:param no: Number of slices the image has to be divided
		"""
        self.image_pieces = image_slicer.slice(name, no)
Exemplo n.º 34
0
def split_and_save_images(image, prefix, directory, split):
	print "Slicing image: {}".format(image.filename)

	# split the image without saving
	try:
		tiles = image_slicer.slice(image.filename, split, save=False)
		if not tiles[1].image:
			print "\tError slicing image"
			return None
	except:
		print "\tError slicing image"
		print "\t", sys.exc_info()[0]
		return None

	# start our storage structure
	split_images = []

	# go through and create the images for return and save
	for tile in tiles:
		# create the split image
		split_image = SplitImage(
			name='{}{}.jpg'.format(prefix, tile.number),
			top=tile.coords[1],
			left=tile.coords[0],
			width=tile.image.size[0],
			height=tile.image.size[1]
		)

		# save and append to our array
		#print "\tSaving image: {}".format(os.path.join(directory, split_image.name))
		try:
			tile.image.save(
				os.path.join(directory, split_image.name),
				'jpeg'
			)
			split_images.append(split_image)
		except:
			print "\tError saving image!"
			print "\t", sys.exc_info()[0]

	# return the split images array
	return split_images
Exemplo n.º 35
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
Exemplo n.º 36
0
import sys, os

import image_slicer

import time

layers = 5

filein = 'evt.png'

# keep track of total time emlpoyed slicing images
tbegin = time.time()

outpath = '/home/david/Desktop/croft/'
file_prefix = 'tile'

for l in xrange(layers):
    
    image_slicer.slice(filein, 4**(l+1), l+1, True, file_prefix, outpath)
    print 'done slicing level %i -> produced %i images'%(l,4**(l+1))
    os.system('cp %s %s/%s'%(filein,outpath,'tile_0_0_0.png'))

tend = time.time()

dt = tend-tbegin
print 'total time employed: %.02f'%dt
Exemplo n.º 37
0
import numpy as np
from skimage import img_as_float, io
from PIL import Image
import os
import image_slicer

os.chdir('../../Data')

image_slicer.slice('lidar2.png', 100)
image_slicer

stop

im = Image.open('lidar.png').convert("L")
array1 = np.ma.array(im)
array1[array1==255]=np.ma.masked
print array1.shape
print array1
#np.save('array1',array1)

im2 = Image.open('lidar2.png').convert("L")
array2 = np.ma.array(im2)
array2[array2==255]=np.ma.masked
print array2.shape
print array2
#np.save('array1',array1)

array3 = np.add(array1, array2)
print 'add'
array3 = np.divide(array3, 2)
print'divide'
Exemplo n.º 38
0
from PIL import Image
import numpy as np
from numpy import inf

################################ Function load image
'''Open image in python'''

im = Image.open('wood.png').convert('L')
im = np.array(im)

################################# Image slicer
'''Slice big picture into nu. of small blocks'''

import image_slicer
image_slicer.slice('huge_test_image.png', 14)

############################### Histogram plot
'''Image histogram plot'''

figure()
hist(im.flatten(),128)
show()

###################################  Entropy
'''Function to calculate entropy from GCLM'''


def entropy(g):
    con1 = -g
    lcon = np.log(g)
    lcon[lcon == -inf] = 0
Exemplo n.º 39
0
     slicenum = [item for sublist in slicenum for item in sublist]
     slicedf = pd.DataFrame({"sliceidx":sliceidx,"slicenum":slicenum})
     
     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]
Exemplo n.º 40
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'
Exemplo n.º 41
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()

Exemplo n.º 42
0
    all_files.append(fnames)
    reasons.append(reason)


for subject_index in range(len(all_files)):
    similarity = []
    non_similarity = []
    print subject_index
    # print reasons[subject_index]
    # print "---"
    differences = []
    for subject_index2 in range(subject_index+1,min(len(all_files),subject_index+7)):
        per_image_difference = []

        for fname1 in all_files[subject_index]:
            image_slicer.slice(image_directory+fname1, 4)
            base_fname1 = fname1[:-4]
            for fname2 in all_files[subject_index2]:
                image_slicer.slice(image_directory+fname2, 4)
                base_fname2 = fname2[:-4]

                per_tile_diff = []
                for xtile in range(1,3):
                    for ytile in range(1,3):
                        fname1 = base_fname1+"_0"+str(xtile)+"_0"+str(ytile)+".png"
                        fname2 = base_fname2+"_0"+str(xtile)+"_0"+str(ytile)+".png"



                        # print image_directory+fname1
                        f1 = cv2.imread(image_directory+fname1)
Exemplo n.º 43
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))