Esempio n. 1
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)
Esempio n. 2
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
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)
    def detectClicked(self):
        if self.image1 == "":
            self.output.insertPlainText("! Error: Enter first image\n")
        elif self.image2 == "":
            self.output.insertPlainText("! Error: Enter second image\n")
        else:
            self.output.insertPlainText(">>> Detection Started\n")
            slices_of_img1 = slice_image(self.image1, self.NUMBER_OF_SLICES,
                                         'slices_of_img1')
            slices_of_img2 = slice_image(self.image2, self.NUMBER_OF_SLICES,
                                         'slices_of_img2')
            new_slices = []
            slice_index = 1
            for img1, img2 in zip(slices_of_img1, slices_of_img2):
                output_photo = main(img1.filename, img2.filename,
                                    self.result_path)
                new_slices.append(
                    Tile(output_photo, img1.number, img1.position,
                         img1.coords))
                print('slice [{}/{}] processed'.format(slice_index,
                                                       self.NUMBER_OF_SLICES))
                slice_index += 1
                del (output_photo)

            image = join(tuple(new_slices))
            image.save('output.png')
            image.show()
Esempio n. 5
0
def convertToBW(model, originalWidth, originalHeight):
    for filename in glob.glob('res/*.*'):
        temp=[]
        img = cv2.imread(filename)
        temp.append(np.array(img))
        result = model.predict(np.asarray(temp))
        result = np.reshape(result, (128, 128))
        cv2.imwrite("generatedImages/"+filename,result)

    files = os.listdir('generatedImages/res/')
    files.sort()
    restiles = []
    for filename in files:
        filename = 'res/'+filename
        for tile in tiles:
            if tile.filename == filename:
                tile.image = Image.open('generatedImages/'+filename)
                restiles.append(tile)
                break
    print(originalWidth, originalHeight)            
    res = image_slicer.join(restiles)
    res = res.resize((originalWidth, originalHeight), Image.ANTIALIAS)
    res.save('res.png')
    
    for filename in files:
        os.remove('generatedImages/res/'+filename)
    for filename in glob.glob('res/*.*'):
        os.remove(filename)
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)
Esempio n. 7
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
Esempio n. 8
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
Esempio n. 9
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()
Esempio n. 10
0
def reassemble_image(t, slice_size = (73,73), rows = 2, cols = 2):
    tiles = [] # The tiles of the image to be assembled
    number = 0
    for j in range(0,rows):
        for i in range(0,cols):
            coord_x = i*slice_size[0]
            coord_y = j*slice_size[1]
            coords = (coord_x, coord_y)
            position = (i+1,j+1)
            tile = image_slicer.Tile(t[number], number, position, coords)
            tiles.append(tile)
            number+=1
    res = image_slicer.join(tuple(tiles))
    res.save("Final.png")
Esempio n. 11
0
def find_image(url, dirName):
    try:
        request = urllib.request.Request(url + ".json")
        with urllib.request.urlopen(request) as url:
            data = json.loads(url.read().decode())
            try:
                for values in data['readableProduct']['pageStructure'].items():
                    if type(values) is not str:
                        for value in values:
                            if type(value) is not str:
                                count = 1
                                for obj in value:
                                    if obj['type'] == 'main':
                                        name = '{}.png'.format(count)
                                        fullfilename = os.path.join(
                                            dirName, name)
                                        urlretrieve(obj['src'], fullfilename)
                                        count = count + 1
            except:
                return False
        for i in range(1, count):
            name = '{}.png'.format(i)
            fullNewFileName = os.path.join(dirName, name)
            im = Image.open(fullNewFileName)
            width, height = im.size
            left = width - width
            top = height - height
            right = width - 5
            bottom = height
            im1 = im.crop((left, top, right, bottom))
            im1.save(fullNewFileName)
            tiles = image_slicer.slice(fullNewFileName, 16, save=False)
            tiles[1].image, tiles[4].image = tiles[4].image, tiles[1].image
            tiles[2].image, tiles[8].image = tiles[8].image, tiles[2].image
            tiles[3].image, tiles[12].image = tiles[12].image, tiles[3].image
            tiles[7].image, tiles[13].image = tiles[13].image, tiles[7].image
            tiles[11].image, tiles[14].image = tiles[14].image, tiles[11].image
            tiles[6].image, tiles[9].image = tiles[9].image, tiles[6].image

            image = join(tiles)
            name = '{}.png'.format(i)
            fullNewFileName = os.path.join(dirName, name)
            image.save(fullNewFileName)
        return True

    except:
        return False
Esempio n. 12
0
def main_function(original_image_filename, deformed_image_filename):
    original_image = Image.open(original_image_filename)
    deformed_image = Image.open(deformed_image_filename)
    # расчет количества блоков
    n = 64
    width, height = original_image.size
    col = math.ceil(width / n)
    row = math.ceil(height / n)

    # пороговая величина
    threshold = n * 0.15

    # разбитие изображений на блоки
    orig_img_tiles = image_slicer.slice(original_image_filename,
                                        col=col,
                                        row=row,
                                        save=False)
    deform_img_tiles = image_slicer.slice(deformed_image_filename,
                                          col=col,
                                          row=row,
                                          save=False)

    for orig_block, deform_block in zip(orig_img_tiles, deform_img_tiles):
        # getting block hash
        orig_hash = myimagehash.phash_simple(orig_block.image)
        deform_hash = myimagehash.phash_simple(deform_block.image)

        # hide a message(hash) in images with the LSB
        orig_block.image = lsb.hide(orig_block.image, str(orig_hash))
        deform_block.image = lsb.hide(deform_block.image, str(deform_hash))

        # Find a message(hash) in images with the LSB
        decoded_orig_hash = lsb.reveal(orig_block.image.copy())
        decoded_deform_hash = lsb.reveal(deform_block.image.copy())

        if hamming_distance(decoded_orig_hash,
                            decoded_deform_hash) > threshold:
            deform_block.image = deform_block.image.convert("L")

    result_image = image_slicer.join(deform_img_tiles, width, height)
    result_image.save("./images/result.png")

    original_image.show()
    deformed_image.show()
    result_image.show()
Esempio n. 13
0
def find_image_pocket(url, dirName):
    try:
        try:
            with open('cookie.txt') as f:
                lines = f.readlines()
                print(type("".join(lines)))
        except:
            return False
        request = urllib.request.Request(url + ".json")
        request.add_header("Cookie", "".join(lines))
        with urllib.request.urlopen(request) as url:
            data = json.loads(url.read().decode())
            try:
                for values in data['readableProduct']['pageStructure'].items():
                    if type(values) is not str:
                        for value in values:
                            if type(value) is not str:
                                count = 1
                                for obj in value:
                                    if obj['type'] == 'main':
                                        name = '{}.png'.format(count)
                                        fullfilename = os.path.join(dirName, name)
                                        urlretrieve(obj['src'], fullfilename)
                                        count = count + 1
            except:
                return False
        for i in range(1, count):
            name = '{}.png'.format(i)
            fullfilename = os.path.join(dirName, name)
            tiles = image_slicer.slice(fullfilename, 16, save=False)
            tiles[1].image, tiles[4].image = tiles[4].image, tiles[1].image
            tiles[2].image, tiles[8].image = tiles[8].image, tiles[2].image
            tiles[3].image, tiles[12].image = tiles[12].image, tiles[3].image
            tiles[7].image, tiles[13].image = tiles[13].image, tiles[7].image
            tiles[11].image, tiles[14].image = tiles[14].image, tiles[11].image
            tiles[6].image, tiles[9].image = tiles[9].image, tiles[6].image
            image = join(tiles)
            newname = '{}.png'.format(i)
            fullnewfilename = os.path.join(dirName, name)
            image.save(fullnewfilename)
        return True

    except:
        return False
Esempio n. 14
0
def run(inimage):
#resize image 
	basewidth = 1080
	img = PIL.Image.open(inimage)
	wpercent = (basewidth / float(img.size[0]))
	hsize = int((float(img.size[1]) * float(wpercent)))
	img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
	img.save('resized_image.jpg')

	#split image
	tiles = image_slicer.slice('resized_image.jpg',9)
	score=[0,0,0,0,0,0,0,0,0]

	#get least quality tile
	for tile in tiles:
		tile.image.save('tile.jpg')
		score[tile.number-1] = float(subprocess.check_output(['./brisque_cpp/brisquequality','-im','tile.jpg']))
	index=score.index(max(score))

	#get label of image
	classlabel=classify.run(inimage).split(' ', 1)[1]
	print classlabel

	#get classid of label
	searchfile = open("labelidmap.txt", "r")
	for line in searchfile:
		if classlabel in line: classid=int(line.split(':',1)[0])
	searchfile.close()
	print classid

	#perform deepdraw
	#tiles[index].image=deepdraw.run(tiles[index].image, classid)
	image=deepdraw.run(tiles[index].image,classid)
	tiles[index].image=PIL.Image.fromarray(image.astype('uint8'))
	#im.save('new.png')
	im=image_slicer.join(tiles)
	im.save('final.png')
	return True
	'''
	for tile in tiles:
		tile.image.show()
	'''
	''''
Esempio n. 15
0
def create_scramble(images, dir, save_dir):
    '''
    create_scramble(images, dir, save_dir) - Creates a list of scrambled images
    where we split each 256px image into 16x16 tiles and randomly shuffling
        Inputs: [images] is a pandas dataframe where the inner elements have the 
        image names. [dir] is a string representing the base directory of the 
        images to be read. [save_dir] is a string representing the base 
        directory of the scrambled images to be saved.
        Requires: both [dir] and [sae_dir] must be valid directories
    '''
    for img in images['img']:
        tiles = image_slicer.slice(dir+img, 256, save=False)
        tiles_list = list(tiles)
        random.shuffle(tiles_list)
        count = 0
        for tile in tiles:
            tile.image = tiles_list[count].image
            count += 1
        scramble = image_slicer.join(tiles)
        scramble.save(save_dir+img)
Esempio n. 16
0
def main():
    start = time.time()
    # input file name
    input_image = "input_image.jpg"
    
    # load list of source images
    try:
        source_dir = "shrunk_sources"
        sources = os.listdir(os.path.join(path, source_dir))
    except:
        print("Unable to load source images")
        sys.exit()
    
    # create an image grid 
    grid = image_slicer.slice(input_image, NUM_TILES, save=False)

    # calculate average rbg from tiles, save in dictionary
    avg_tile_rgb = average_tile_rbg(grid)
    
    # calculate average rbg from source images
    avg_source_rgb = average_source_rgb(sources) 
    
    # match source to input tile
    match_dict = match_source(avg_tile_rgb, avg_source_rgb)
    
    # replace tiles with match
    for tile in grid:
        match = match_dict[tile]
        match_img = Image.open(os.path.join(path, source_dir, match))
        tile.image = match_img
           
    # sew together to make mosaic and crop
    mosaic = join(grid)
       
    # save mosaic
    mosaic.save('photomosaic.jpg')
    end = time.time()
    print(end-start)
Esempio n. 17
0
def piece_joiner(tiles, n_pieces, img_save_name, scramble_jigsaw=True):
    """
    :param tiles: List of tiles with attributes containing an image
    :param n_pieces: Amount of pieces inside our jigsaw puzzle
    :param img_save_name: The name of the newly saved image
    :param scramble_jigsaw: Boolean to scramble the jigsaw or not
    """

    rand_tiles = list(tiles)

    if scramble_jigsaw:
        # Immutable tiles >> transform the tiles in 1,2,3 .. format
        random_order = [i for i in range(n_pieces)]

        random.shuffle(random_order)

        temp = copy.deepcopy(rand_tiles)

        for i in range(n_pieces):
            rand_tiles[i].image = temp[random_order[i]].image

    image = image_slicer.join(tuple(rand_tiles))
    image.save(img_save_name)
Esempio n. 18
0
def main():
    # Load Temp Values
    temps = load_temp_values('StackImages/raw1.txt')
    print(len(temps[0]))
    # Store Temp Values, Sort through array
    tiles_data = []
    # Row 1
    num1=0; max1=0; min1=temps[0][0];
    num2=0; max2=0; min2=temps[0][20];
    num3=0; max3=0; min3=temps[0][40];
    num4=0; max4=0; min4=temps[0][60];
    num5=0; max5=0; min5=temps[0][80];
    num6=0; max6=0; min6=temps[0][100];
    num7=0; max7=0; min7=temps[0][120];
    num8=0; max8=0; min8=temps[0][140];
    # Row 2
    num9=0; max9=0; min9=temps[20][0];
    num10=0; max10=0; min10=temps[20][20];
    num11=0; max11=0; min11=temps[20][40];
    num12=0; max12=0; min12=temps[20][60];
    num13=0; max13=0; min13=temps[20][80];
    num14=0; max14=0; min14=temps[20][100];
    num15=0; max15=0; min15=temps[20][120];
    num16=0; max16=0; min16=temps[20][140];
    # Row 3
    num17=0; max17=0; min17=temps[40][0];
    num18=0; max18=0; min18=temps[40][20];
    num19=0; max19=0; min19=temps[40][40];
    num20=0; max20=0; min20=temps[40][60];
    num21=0; max21=0; min21=temps[40][80];
    num22=0; max22=0; min22=temps[40][100];
    num23=0; max23=0; min23=temps[40][120];
    num24=0; max24=0; min24=temps[40][140];
    # Row 4
    num25=0; max25=0; min25=temps[60][0];
    num26=0; max26=0; min26=temps[60][20];
    num27=0; max27=0; min27=temps[60][40];
    num28=0; max28=0; min28=temps[60][60];
    num29=0; max29=0; min29=temps[60][80];
    num30=0; max30=0; min30=temps[60][100];
    num31=0; max31=0; min31=temps[60][120];
    num32=0; max32=0; min32=temps[60][140];
    # Row 5
    num33=0; max33=0; min33=temps[80][0];
    num34=0; max34=0; min34=temps[80][20];
    num35=0; max35=0; min35=temps[80][40];
    num36=0; max36=0; min36=temps[80][60];
    num37=0; max37=0; min37=temps[80][80];
    num38=0; max38=0; min38=temps[80][100];
    num39=0; max39=0; min39=temps[80][120];
    num40=0; max40=0; min40=temps[80][140];
    # Row 6
    num41=0; max41=0; min41=temps[100][0];
    num42=0; max42=0; min42=temps[100][20];
    num43=0; max43=0; min43=temps[100][40];
    num44=0; max44=0; min44=temps[100][60];
    num45=0; max45=0; min45=temps[100][80];
    num46=0; max46=0; min46=temps[100][100];
    num47=0; max47=0; min47=temps[100][120];
    num48=0; max48=0; min48=temps[100][140];

    ## Divide Data into 20X20 Squares
    for idx in range(0,len(temps[0])):
        row = []
        for idy in range(0,len(temps)):
            #find_temp_max(a,b,c,d)
            # Case 1: Tile 1 Quadrant
            if (idx < 20 and idy < 20):
                num1+=1;
                #print("Before in K:"+str(temps[idy][idx]))
                temp = temps[idy][idx]/100 - 273.15
                #print("After in C:"+str(temp))
                #print(temp)
                if (temp > max1):
                    max1 = temp
                elif (temp < min1):
                    min1 = temp
                #print("Tile 1 Quadrant")
                row.append(temp)
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 2: Tile 2 Quadrant
            elif (idx >= 20 and idx < 40 and idy < 20):
                num2+=1;
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max2):
                    max2 = temp
                elif (temp < min2):
                    min2 = temp
                #print("Tile 2 Quadrant")
                row.append(temp)
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 3: Tile 3 Quadrant
            elif (idx >= 40 and idx < 60 and idy < 20):
                num3+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max3):
                    max3 = temp
                elif (temp < min3):
                    min3 = temp
                #print("Tile 3 Quadrant")
                row.append(temp)
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 4: Tile 4 Quadrant
            elif (idx >= 60 and idx < 80 and idy < 20):
                num4+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max4):
                    max4 = temp
                elif (temp < min4):
                    min4 = temp
                #print("Tile 4 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 5: Tile 5 Quadrant
            elif (idx >= 80 and idx < 100 and idy < 20):
                num5+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max5):
                    max5 = temp
                elif (temp < min5):
                    min5 = temp
                #print("Tile 5 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 6: Tile 6 Quadrant
            elif (idx >= 100 and idx < 120 and idy < 20):
                num6+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max6):
                    max6 = temp
                elif (temp < min6):
                    min6 = temp
                #print("Tile 6 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 7: Tile 7 Quadrant
            elif (idx >= 120 and idx < 140 and idy < 20):
                num7+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max7):
                    max7 = temp
                elif (temp < min7):
                    min7 = temp
                #print("Tile 7 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 8: Tile 8 Quadrant
            elif (idx >= 140 and idx < 160 and idy < 20):
                num8+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max8):
                    max8 = temp
                elif (temp < min8):
                    min8 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 9: Tile 9 Quadrant
            elif (idx < 20 and idy >= 20 and idy < 40):
                num9+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max9):
                    max9 = temp
                elif (temp < min9):
                    min9 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 10: Tile 10 Quadrant
            elif (idx >= 20 and idx < 40 and idy >= 20 and idy < 40):
                num10+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max10):
                    max10 = temp
                elif (temp < min10):
                    min10 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 11: Tile 11 Quadrant
            elif (idx >= 40 and idx < 60 and idy >= 20 and idy < 40):
                num11+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max11):
                    max11 = temp
                elif (temp < min11):
                    min11 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 12: Tile 12 Quadrant
            elif (idx >= 60 and idx < 80 and idy >= 20 and idy < 40):
                    num12+=1
                    temp = temps[idy][idx]/100 - 273.15
                    if (temp > max12):
                        max12 = temp
                    elif (temp < min12):
                        min12 = temp
                    #print("Tile 8 Quadrant")
                    row.append(temps[idy][idx])
                    #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 13: Tile 13 Quadrant
            elif (idx >= 80 and idx < 100 and idy >= 20 and idy < 40):
                    num13+=1
                    temp = temps[idy][idx]/100 - 273.15
                    if (temp > max13):
                        max13 = temp
                    elif (temp < min13):
                        min13 = temp
                    #print("Tile 8 Quadrant")
                    row.append(temps[idy][idx])
                    #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 14: Tile 14 Quadrant
            elif (idx >= 100 and idx < 120 and idy >= 20 and idy < 40):
                    num14+=1
                    temp = temps[idy][idx]/100 - 273.15
                    if (temp > max14):
                        max14 = temp
                    elif (temp < min14):
                        min14 = temp
                    #print("Tile 8 Quadrant")
                    row.append(temps[idy][idx])
                    #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 15: Tile 15 Quadrant
            elif (idx >= 120 and idx < 140 and idy >= 20 and idy < 40):
                    num15+=1
                    temp = temps[idy][idx]/100 - 273.15
                    if (temp > max15):
                        max15 = temp
                    elif (temp < min15):
                        min15 = temp
                    #print("Tile 8 Quadrant")
                    row.append(temps[idy][idx])
                    #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 16: Tile 16 Quadrant
            elif (idx >= 140 and idx < 160 and idy >= 20 and idy < 40):
                    num16+=1
                    temp = temps[idy][idx]/100 - 273.15
                    if (temp > max16):
                        max16 = temp
                    elif (temp < min16):
                        min16 = temp
                    #print("Tile 8 Quadrant")
                    row.append(temps[idy][idx])
                    #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 17: Tile 17 Quadrant
            elif (idx < 20 and idy >= 40 and idy < 60):
                    num17+=1
                    temp = temps[idy][idx]/100 - 273.15
                    if (temp > max17):
                        max17 = temp
                    elif (temp < min17):
                        min17 = temp
                    #print("Tile 8 Quadrant")
                    row.append(temps[idy][idx])
                    #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 18: Tile 18 Quadrant
            elif (idx >= 20 and idx < 40 and idy >= 40 and idy < 60):
                    num18+=1
                    temp = temps[idy][idx]/100 - 273.15
                    if (temp > max18):
                        max18 = temp
                    elif (temp < min18):
                        min18 = temp
                    #print("Tile 8 Quadrant")
                    row.append(temps[idy][idx])
                    #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 19: Tile 19 Quadrant
            elif (idx >= 40 and idx < 60 and idy >= 40 and idy < 60):
                    num19+=1
                    temp = temps[idy][idx]/100 - 273.15
                    if (temp > max19):
                        max19 = temp
                    elif (temp < min19):
                        min19 = temp
                    #print("Tile 8 Quadrant")
                    row.append(temps[idy][idx])
                    #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 20: Tile 20 Quadrant
            elif (idx >= 60 and idx < 80 and idy >= 40 and idy < 60):
                    num20+=1
                    temp = temps[idy][idx]/100 - 273.15
                    if (temp > max20):
                        max20 = temp
                    elif (temp < min20):
                        min20 = temp
                    #print("Tile 8 Quadrant")
                    row.append(temps[idy][idx])
                    #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 21: Tile 21 Quadrant
            elif (idx >= 80 and idx < 100 and idy >= 40 and idy < 60):
                    num21+=1
                    temp = temps[idy][idx]/100 - 273.15
                    if (temp > max21):
                        max21 = temp
                    elif (temp < min21):
                        min21 = temp
                    #print("Tile 8 Quadrant")
                    row.append(temps[idy][idx])
                    #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 22: Tile 22 Quadrant
            elif (idx >= 100 and idx < 120 and idy >= 40 and idy < 60):
                    num22+=1
                    temp = temps[idy][idx]/100 - 273.15
                    if (temp > max22):
                        max22 = temp
                    elif (temp < min22):
                        min22 = temp
                    #print("Tile 8 Quadrant")
                    row.append(temps[idy][idx])
                    #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 23: Tile 23 Quadrant
            elif (idx >= 120 and idx < 140 and idy >= 40 and idy < 60):
                    num23+=1
                    temp = temps[idy][idx]/100 - 273.15
                    if (temp > max23):
                        max23 = temp
                    elif (temp < min23):
                        min23 = temp
                    #print("Tile 8 Quadrant")
                    row.append(temps[idy][idx])
                    #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 24: Tile 24 Quadrant
            elif (idx >= 140 and idx < 160 and idy >= 40 and idy < 60):
                    num24+=1
                    temp = temps[idy][idx]/100 - 273.15
                    if (temp > max24):
                        max24 = temp
                    elif (temp < min24):
                        min24 = temp
                    #print("Tile 8 Quadrant")
                    row.append(temps[idy][idx])
                    #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 25: Tile 25 Quadrant
            elif (idx < 20 and idy >= 60 and idy < 80):
                    num25+=1
                    temp = temps[idy][idx]/100 - 273.15
                    if (temp > max25):
                        max25 = temp
                    elif (temp < min25):
                        min25 = temp
                    #print("Tile 8 Quadrant")
                    row.append(temps[idy][idx])
                    #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 26: Tile 26 Quadrant
            elif (idx >= 20 and idx < 40 and idy >= 60 and idy < 80):
                num26+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max26):
                    max26 = temp
                elif (temp < min26):
                    min26 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 27: Tile 27 Quadrant
            elif (idx >= 40 and idx < 60 and idy >= 60 and idy < 80):
                num27+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max27):
                    max27 = temp
                elif (temp < min27):
                    min27 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 28: Tile 28 Quadrant
            elif (idx >= 60 and idx < 80 and idy >= 60 and idy < 80):
                num28+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max28):
                    max28 = temp
                elif (temp < min28):
                    min28 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 29: Tile 29 Quadrant
            elif (idx >= 80 and idx < 100 and idy >= 60 and idy < 80):
                num29+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max29):
                    max29 = temp
                elif (temp < min29):
                    min29 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 30: Tile 30 Quadrant
            elif (idx >= 100 and idx < 120 and idy >= 60 and idy < 80):
                num30+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max30):
                    max30 = temp
                elif (temp < min30):
                    min30 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 31: Tile 31 Quadrant
            elif (idx >= 120 and idx < 140 and idy >= 60 and idy < 80):
                num31+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max31):
                    max31 = temp
                elif (temp < min31):
                    min31 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 32: Tile 32 Quadrant
            elif (idx >= 140 and idx < 160 and idy >= 60 and idy < 80):
                num32+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max32):
                    max32 = temp
                elif (temp < min32):
                    min32 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 33: Tile 33 Quadrant
            elif (idx < 20 and idy >= 80 and idy < 100):
                num33+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max33):
                    max33 = temp
                elif (temp < min33):
                    min33 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 34: Tile 34 Quadrant
            elif (idx >= 20 and idx < 40 and idy >= 80 and idy < 100):
                num34+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max34):
                    max34 = temp
                elif (temp < min34):
                    min34 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 35: Tile 35 Quadrant
            elif (idx >= 40 and idx < 60 and idy >= 80 and idy < 100):
                num35+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max35):
                    max35 = temp
                elif (temp < min35):
                    min35 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 36: Tile 36 Quadrant
            elif (idx >= 60 and idx < 80 and idy >= 80 and idy < 100):
                num36+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max36):
                    max36 = temp
                elif (temp < min36):
                    min36 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 37: Tile 37 Quadrant
            elif (idx >= 80 and idx < 100 and idy >= 80 and idy < 100):
                num37+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max37):
                    max37 = temp
                elif (temp < min37):
                    min37 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 38: Tile 38 Quadrant
            elif (idx >= 100 and idx < 120 and idy >= 80 and idy < 100):
                num38+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max38):
                    max38 = temp
                elif (temp < min38):
                    min38 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 39: Tile 39 Quadrant
            elif (idx >= 120 and idx < 140 and idy >= 80 and idy < 100):
                num39+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max39):
                    max39 = temp
                elif (temp < min39):
                    min39 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 40: Tile 40 Quadrant
            elif (idx >= 140 and idx < 160 and idy >= 80 and idy < 100):
                num40+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max40):
                    max40 = temp
                elif (temp < min40):
                    min40 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 41: Tile 41 Quadrant
            elif (idx < 20 and idy >= 100 and idy < 120):
                num41+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max41):
                    max41 = temp
                elif (temp < min41):
                    min41 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 42: Tile 42 Quadrant
            elif (idx >= 20 and idx < 40 and idy >= 100 and idy < 120):
                num42+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max42):
                    max42 = temp
                elif (temp < min42):
                    min42 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 43: Tile 43 Quadrant
            elif (idx >= 40 and idx < 60 and idy >= 100 and idy < 120):
                num43+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max43):
                    max43 = temp
                elif (temp < min43):
                    min43 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 44: Tile 44 Quadrant
            elif (idx >= 60 and idx < 80 and idy >= 100 and idy < 120):
                num44+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max44):
                    max44 = temp
                elif (temp < min44):
                    min44 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 45: Tile 45 Quadrant
            elif (idx >= 80 and idx < 100 and idy >= 100 and idy < 120):
                num45+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max45):
                    max45 = temp
                elif (temp < min37):
                    min45 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 46: Tile 46 Quadrant
            elif (idx >= 100 and idx < 120 and idy >= 100 and idy < 120):
                num46+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max46):
                    max46 = temp
                elif (temp < min46):
                    min46 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 47: Tile 47 Quadrant
            elif (idx >= 120 and idx < 140 and idy >= 100 and idy < 120):
                num47+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max47):
                    max47 = temp
                elif (temp < min47):
                    min47 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))
            # Case 48: Tile 48 Quadrant
            elif (idx >= 140 and idx < 160 and idy >= 100 and idy < 120):
                num48+=1
                temp = temps[idy][idx]/100 - 273.15
                if (temp > max48):
                    max48 = temp
                elif (temp < min48):
                    min48 = temp
                #print("Tile 8 Quadrant")
                row.append(temps[idy][idx])
                #print("Dimension: "+str((idx,idy))+" Temperature: "+str(temps[idx][idy]))



        tiles_data.append(row)

    ## Print Number of Saved Elements in Each Tile
    #print(num1);print(num2);print(num3);print(num4);print(num5);print(num6)

    ## Check Max and Min Values
    result = []; results = [];
    # Row 1
    result.append(temp_range_check("1",min1,max1+50))
    result.append(temp_range_check("2",min2,max2))
    result.append(temp_range_check("3",min3,max3))
    result.append(temp_range_check("4",min4,max4))
    result.append(temp_range_check("5",min5,max5))
    result.append(temp_range_check("6",min6-51,max6))
    result.append(temp_range_check("7",min7,max7))
    result.append(temp_range_check("8",min8,max8))
    results.append(result)
    result = [];
    result.append(temp_range_check("9",min9,max9))
    result.append(temp_range_check("10",min10,max10))
    result.append(temp_range_check("11",min11,max11))
    result.append(temp_range_check("12",min12,max12))
    result.append(temp_range_check("13",min13,max13))
    result.append(temp_range_check("14",min13,max14))
    result.append(temp_range_check("15",min13,max15))
    result.append(temp_range_check("16",min13,max16))
    results.append(result)
    result = [];
    result.append(temp_range_check("17",min17,max17))
    result.append(temp_range_check("18",min18,max18))
    result.append(temp_range_check("19",min19,max19))
    result.append(temp_range_check("20",min20,max20))
    result.append(temp_range_check("21",min21,max21))
    result.append(temp_range_check("22",min22,max22))
    result.append(temp_range_check("23",min23,max23))
    result.append(temp_range_check("24",min24,max24))
    results.append(result)
    result = [];
    result.append(temp_range_check("25",min25,max25))
    result.append(temp_range_check("26",min26,max26))
    result.append(temp_range_check("27",min27,max27))
    result.append(temp_range_check("28",min28,max28))
    result.append(temp_range_check("29",min29,max29))
    result.append(temp_range_check("30",min30,max30))
    result.append(temp_range_check("31",min31,max31))
    result.append(temp_range_check("32",min32,max32))
    results.append(result)
    result = [];

    print(max24)



    ## Load Image, Remove Whitespace
    # I tried a few different methods for removing the whitespace which arises from
    # saving the PIL image. This custom trim() function seems to work best. - Justin 2/27/19
    def trim(im):
        bg = Image.new(im.mode, im.size, im.getpixel((0,0))) # New Image
        diff = ImageChops.difference(im, bg) # Diff w background
        diff = ImageChops.add(diff, diff, 2.0, -100)
        bbox = diff.getbbox()
        if bbox:
            return im.crop(bbox) # Return Trimmed Image object

    ## Save Trimmed Image
    im = Image.open("output.png") # Open whitespace image
    im = trim(im) # Call trim() function
    im.show() # Show
    im.save("output.png") # Save image

    ## Call Image_Slicer
    num_tiles = 48
    tiles = image_slicer.slice('output.png',num_tiles, save=False) # Slice into tiles
    image_slicer.save_tiles(tiles,directory='Outputs',prefix='slice',format='png') # Save tiles

    ## Overlay Tiles in Single Joined Image
    for tile in tiles:
        overlay = ImageDraw.Draw(tile.image)
        overlay.text((5,5),str(tile.number),(255,255,255),ImageFont.load_default()) # Draw #s on the image
    image_slicer.save_tiles(tiles,directory='Outputs/NumberedTiles',prefix='slice',format='png') # Each numbered tiles
    image = join(tiles) # Join tiled images
    image.save('watch-join.png') # Save final image
Esempio n. 19
0
if not os.path.exists(cwd):
    os.mkdir(cwd)
if not os.path.exists(cwtd):
    os.mkdir(cwtd)
print(f"HDizing emotes for: {config.t_streamer}")

for image in sjp['emoticons']:
    img_url = f"https://static-cdn.jtvnw.net/emoticons/v1/{image['id']}/3.0"
    c_emote_filename = f"{image['regex']}.png"
    c_emote_wpath = Path.joinpath(cwtd).joinpath(c_emote_filename)
    print(f"Downloading: {image['regex']}:{img_url} Image saved to: {c_emote_wpath}")
    c_emote = requests.get(img_url)
    open(c_emote_wpath, 'wb').write(c_emote.content)
    e_tiles = image_slicer.slice(c_emote_wpath, config.pixel_count)
    for tile in e_tiles:
        pixel = ColorThief(tile.filename)
        try:
            fill_color = pixel.get_color(quality=config.color_pick_quality)
        except:
            fill_color = (255,255,255)
        tile_temp = cwd.joinpath(tile.filename)
        tile_image = Image.open(tile.filename)
        pil_image = Image.new("RGB", (tile_image.size[0],tile_image.size[1]), color=fill_color)
        tile.image = pil_image
    hd_image = image_slicer.join(e_tiles)
    for size in (28,56,112):
        save_image = hd_image.resize((size,size))
        c_emote_fpath = Path.joinpath(cwd).joinpath(f"{image['regex']}_hd_{size}.png")
        print(f"Saved 'HD' emote to {c_emote_fpath}")
        save_image.save(c_emote_fpath, "PNG")
def main():

    import argparse

    # Parse command line arguments
    parser = argparse.ArgumentParser(
        description='Train Mask R-CNN on satellite images.')
    parser.add_argument("--size",
                        metavar="size",
                        default="small",
                        help="'large' or 'small' images")

    args = parser.parse_args()
    print("Image Type: ", args.size)



    # Root directory of the project
    ROOT_DIR = os.path.abspath("../")

    # Import Mask RCNN
    sys.path.append(ROOT_DIR)  # To find local version of the library
    from mrcnn import utils
    import mrcnn.model as modellib
    from mrcnn import visualize
    # from mrcnn.visualize import save_image # added by JX

    # Import COCO config
    sys.path.append(os.path.join(ROOT_DIR, "samples/coco/"))  # To find local version
    import sate

    #matplotlib inline

    # Directory to save logs and trained model
    MODEL_DIR = os.path.join(ROOT_DIR, "logs")

    # Local path to trained weights file
    COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_sate_b2_0071.h5")
    #COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_sate_0055.h5")
    #COCO_MODEL_PATH = os.path.join(ROOT_DIR, "crowdai_pretrained_weights.h5")
    
    # # Download COCO trained weights from Releases if needed
    # if not os.path.exists(COCO_MODEL_PATH):
    #     utils.download_trained_weights(COCO_MODEL_PATH)

    # Directory of images to run detection on
    # IMAGE_DIR = os.path.join(ROOT_DIR, "images")
    InIMAGE_DIR = "/home/ashwin/Desktop/Test/input"
    OutIMAGE_DIR = "/home/ashwin/Desktop/Test/output"
    if not os.path.isdir(OutIMAGE_DIR):
        os.makedirs(OutIMAGE_DIR)

    if args.size == 'large':
        Image.MAX_IMAGE_PIXELS = 1600 * 1600 * 10 * 10
        img_name = os.listdir(InIMAGE_DIR)[0]
        img = os.path.join(InIMAGE_DIR, img_name)
        num_tiles = 64
        print("Slicing image into {} slices".format(num_tiles))
        tiles = image_slicer.slice(img, num_tiles)

    ## Configurations

    class InferenceConfig(sate.CocoConfig):
        # Set batch size to 1 since we'll be running inference on
        # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
        GPU_COUNT = 1
        IMAGES_PER_GPU = 1

    config = InferenceConfig()
    config.display()

    ## Create Model and Load Trained Weights

    # Create model object in inference mode.
    model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)

    model_json = model.KM.to_json()
    with open("model.json", "w") as json_file:
        json_file.write(model_json)
    
    print("Loading weights from:",COCO_MODEL_PATH)

    # Load weights trained on MS-COCO
    model.load_weights(COCO_MODEL_PATH, by_name=True)#, exclude=["mrcnn_bbox_fc", "mrcnn_class_logits", "mrcnn_mask"])



    ## Class Names
    # COCO Class names
    # Index of the class in the list is its ID. For example, to get ID of
    # the teddy bear class, use: class_names.index('teddy bear')
    # class_names = ['Plane', 'Ships', 'Running_Track', 'Helicopter', 'Vehicles', 'Storage_Tanks', 'Tennis_Court',
    #                'Basketball_Court', 'Bridge', 'Roundabout', 'Soccer_Field', 'Swimming_Pool', 'baseball_diamond',
    #                'Buildings', 'Road', 'Tree', 'People', 'Hangar', 'Parking_Lot', 'Airport', 'Motorcycles', 'Flag',
    #                'Sports_Stadium', 'Rail_(for_train)', 'Satellite_Dish', 'Port', 'Telephone_Pole',
    #                'Intersection/Crossroads', 'Shipping_Container_Lot', 'Pier', 'Crane', 'Train', 'Tanks', 'Comms_Tower',
    #                'Cricket_Pitch', 'Submarine', 'Radar', 'Horse_Track', 'Hovercraft', 'Missiles', 'Artillery',
    #                'Racing_Track', 'Vehicle_Sheds', 'Fire_Station', 'Power_Station', 'Refinery', 'Mosques', 'Helipads',
    #                'Shipping_Containers', 'Runway', 'Prison', 'Market/Bazaar', 'Police_Station', 'Quarry', 'School',
    #                'Graveyard', 'Well', 'Rifle_Range', 'Farm', 'Train_Station', 'Crossing_Point', 'Telephone_Line',
    #                'Vehicle_Control_Point', 'Warehouse', 'Body_Of_water', 'Hospital', 'Playground', 'Solar_Panel']

    class_names = ['BG','building']

    # model_filename = "MRCNN_spacemodel.pkl"

    # pickle.dump(model,open(model_filename, 'wb'))

    if args.size == 'large':
        for tile in tiles:
            image = skimage.io.imread(tile.filename)
            # remove alpha channel
            image = image[:, :, :3]
    
            results = model.detect([image], verbose=1)
            r = results[0]
        
            fig = visualize.save_instances(image, r['rois'], r['masks'], r['class_ids'], class_names, r['scores'])
    
            plt.imsave(tile.filename,fig)
            tile.image = Image.open(tile.filename)

        image = join(tiles)
        image.save(os.path.join(OutIMAGE_DIR,img_name))


    if args.size == 'small':        
        gt_flag = 0

        # TODO: If any tif files are present, convert them to jpg 

        ## Run Object Detection
        filenames = glob.glob(os.path.join(InIMAGE_DIR, "*.jpg"))
        with open('./coco/annotations_batch1/train.json') as f: # Not needed for inference
            gj = json.load(f)
        for counter, fl in enumerate(filenames):
            print("counter = {:5d}".format(counter))
            image_name = fl.split('/')[-1]
            output_path = os.path.join(OutIMAGE_DIR, image_name)
            if os.path.isfile(output_path):
                continue

            # image = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names)))
            image = skimage.io.imread(fl)
            # remove alpha channel
            image = image[:, :, :3]

            results = model.detect([image], verbose=1)


            r = results[0]
            # visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], class_names, r['scores'])

        #####################################################################################################
            if gt_flag == 1:
                bbox_actual = []


                print("Image ID:",image_name[:-4])
                for ind in gj['annotations']:
                    if ind['image_id'] == image_name[:-4]:
                        bbox_actual.append(ind['bbox'])
            
        #print("Number of proposals =",len(r['rois']))
        #print("Number of ground truth labels =",len(bbox_actual))

        #print("Proposal1= ",r['rois'][0])
        #print("ActualBBox1= ",bbox_actual[0])

        # Ideally it should be a square matrix with high IOU values in the diagonal
        #iou_mat = bbox_iou(r['rois'],bbox_actual,bb_format="XYWH")
        #print(iou_mat)

        #plt.figure()

        #plt.imshow(iou_mat, cmap="hot",interpolation="nearest")
        #plt.show()
        
        #####################################################################################################


            fig = visualize.save_instances(image, r['rois'], r['masks'], r['class_ids'], class_names, r['scores'])
        # fig.savefig(output_path, bbox_inches='tight', pad_inches=0)

            print("Number of detected buildings =",len(r['rois']))
        
            if gt_flag == 1:
                print("Number of ground truth buildings",len(bbox_actual))



        # print(fig.shape)
            plt.imsave(output_path, fig)
Esempio n. 21
0
def main():
    print "*****************************************************************************************************************"
    print "                                           Remote Sensing Image Analyzer"
    print "*****************************************************************************************************************"
    name = "slice.jpg"
    Tree1 = merkleQuadTree()
    Tree1.imageDivide(name, 256)
    #Initializing the name of the image in the name variable
    name = "slice"
    row = 16
    col = 16
    Tree1.hashList(name, row, col)
    #Calculating the level 3 parent hash and storing it in hash_level3
    Tree1.hash_level3 = Tree1.parent_Hash(Tree1.hash_list)
    #Calculating the level 2 parent hash and storing it in hash_level2
    Tree1.hash_level2 = Tree1.parent_Hash(Tree1.hash_level3)
    #Calculating the level 1 parent hash and storing it in hash_level1
    Tree1.hash_level1 = Tree1.parent_Hash(Tree1.hash_level2)
    #Calculating the level 0 parent hash and storing it in hash_level1
    Tree1.parent_hash = Tree1.parent_Hash(Tree1.hash_level1)
    parent1 = Tree1.parent_hash[0]
    print "Root hash for tree 1:", parent1
    print "The first tree has been built!!!!"
    #The first tree has been built by the above code

    #Starting to implement the second tree!!!
    name = "slice1.jpg"
    Tree2 = merkleQuadTree()
    Tree2.imageDivide(name, 256)
    #Initializing the name of the image in the name variable
    name = "slice1"
    row = 16
    col = 16
    Tree2.hashList(name, row, col)
    #Calculating the level 3 parent hash and storing it in hash_level3
    Tree2.hash_level3 = Tree2.parent_Hash(Tree2.hash_list)
    #Calculating the level 2 parent hash and storing it in hash_level2
    Tree2.hash_level2 = Tree2.parent_Hash(Tree2.hash_level3)
    #Calculating the level 1 parent hash and storing it in hash_level1
    Tree2.hash_level1 = Tree2.parent_Hash(Tree2.hash_level2)
    #Calculating the level 0 parent hash and storing it in hash_level1
    Tree2.parent_hash = Tree2.parent_Hash(Tree2.hash_level1)
    parent2 = Tree2.parent_hash[0]
    print "Root hash for tree 2:", parent2
    print "The second tree has been built!!!!"
    #The second tree has been built by the above code

    #Starting the comparision phase!!!
    if parent1 == parent2:
        print "Both images are same!!!"
    else:
        print "Both images are different"
        count = 0
        #This part of the code finds the pieces of image that are different, grayscales the pieces that are different and joins it back
        for x in range(0, 4, 1):
            if Tree1.hash_level1[x] != Tree2.hash_level1[x]:

                i = 4 * x
                for y in range(i, i + 4, 1):
                    if Tree1.hash_level2[y] != Tree2.hash_level2[y]:
                        p = 4 * y
                        for z in range(p, p + 4, 1):
                            if Tree1.hash_level3[z] != Tree2.hash_level3[z]:
                                m = 4 * z
                                for w in range(m, m + 4):
                                    if Tree1.hash_list[w] != Tree2.hash_list[w]:
                                        count = count + 1
                                        b = Tree1.image_pieces[w].image
                                        Tree1.image_pieces[
                                            w].image = b.convert('LA')
        t = image_slicer.join(Tree1.image_pieces)
        t.save('diffRes.png')
        print "The number of different pieces in the two image are:", count
    # Clean the files created
    os.system('rm slice_*')
    os.system('rm slice1_*')
Esempio n. 22
0
for th in lst:                #create a new list with numbers encrypted. The 1st and 2nd are marked as N and M
       MA = encryption(th[0], sk, dim)
       if (check == 2):
               M = MA
       if (check == 1):
               N = MA   
       if (check == 6):
               P = MA       
       newlst.append((MA, th[1]))
       check +=1

swappedlst = swaptiles (newlst, M, N)
finlst = bynumber(newlst, P)

tiles1 = [None] * len(swappedlst)
for i in range(len(swappedlst)):
       tiles1[i] = swappedlst[i][1]


image = join(tiles1)
image.save("swapped.png")
image.show()

tiles2 = [None] * len(finlst)
for i in range(len(finlst)):
       tiles2[i] = finlst[i][1]

image = join(tiles2)
image.save("onepiece.png")
image.show()
Esempio n. 23
0
def process_image(im, slices):
    tiles = image_slicer.slice(im, slices, save=False)
    for tile in tiles:
        square = tile.image.load()
        replace_pixels(tile.image, square)
    return image_slicer.join(tiles)
Esempio n. 24
0
def combine_tiles(tile_file):
    load_tiles = pickle.load(open(tile_file, 'rb'))
    image_combine = image_slicer.join(load_tiles)
    image_combine.save('combined_image_fullrun3.png')
Esempio n. 25
0
import sys

import PIL
import image_slicer
from PIL import Image
import time
PIL.Image.MAX_IMAGE_PIXELS = 933120000
start_time = time.time()
tiles = image_slicer.open_images_in("E:\yolov5\inference\output")
image = image_slicer.join(tiles)
image.save('E:/yolov5/inference/output_conf_08.png')
print("--- %s seconds ---" % (time.time() - start_time))
Esempio n. 26
0
def main():
    # Print the number of
    # CPUs in the system
    print("Number of CPUs in the system:", cpuCount)

    # for debugging use the small dataset
    images = get_images("./SmallSet_Images/")

    # uncomment the following line to do testing on larger dataset
    # images = get_images("./Sample_Images/")

    # if directories already exist, empty them, else create them
    setup_directories()

    # get the key
    k = get_key()

    # initialize progress bar
    widgets = [
        'Batch Encryption/Decryption: ',
        progressbar.Bar('█'),
        ' (',
        progressbar.ETA(),
        ') ',
    ]
    bar = progressbar.ProgressBar(28, widgets=widgets).start()
    t = 0

    # loop through loaded images and run encryption and decryption
    # timing information is gathered in the encrypt() and decrypt() functions
    for i in images:

        #slice up the image according to the number of cpu threads you have
        tiles = image_slicer.slice(i.f_name, cpuCount, save=False)

        t += 1

        # mark and save the input image to the respective directory
        label_and_save(i.image, "Original Image", i.f_name, O_path)

        for tile in tiles:
            #save tile data
            tilesMap[tile.number] = Tile_Data(tile.image, tile.number)
            # initialize message variable for input to encryption function (turn each tile into a byte array)
            msg = np.array(tile.image).tobytes()
            #create new thread & pass along the chunk with the key
            newThread = encryptionThread(tile.number, msg, k, tile, 0)
            newThread.start()
            threads.append(newThread)

        #wait for all of the threads to finish their work
        print("Waiting for all the threads to finish...")
        for thread in threads:
            thread.join()

        # join all of the tiles and save it to its respective directory
        image = join(tiles)
        image.save(".\\Encrypted_Images\\" + str(random.randint(1, 1000000)) +
                   ".png")
        #build_and_save(i, image, 0)

        #start decryption process
        for tile in tiles:
            msg = np.array(tile.image).tobytes()

            threads[tile.number - 1] = encryptionThread(
                tile.number, msg, k, tile, 1)
            threads[tile.number - 1].start()

        print("Number of threads active: " + str(threading.active_count()))

        #wait for all of the threads to finish their work
        print("Waiting for all the threads to finish...")
        for thread in threads:
            thread.join()

        image = join(tiles)
        image.save(".\\Decrypted_Images\\" + str(random.randint(1, 1000000)) +
                   ".png")

        # create an image from the cleartext and save it to its respective directory
        ##build_and_save(i, cleartext, 1)
        bar.update(t)
    print("\n\n")

    # output the results
    print_results(len(images), enc_times, dec_times)
Esempio n. 27
0
 def setUp(self):
     self.original = Image.open(TEST_IMAGE)
     self.reconstituted = join(slice(TEST_IMAGE, NUMBER_TILES, save=False))
        tile.image = Image.composite(newBg_right, newBg_left, newBg_right)

    if ((tile.number + i) in open_tile) and ((tile.number + j)
                                             not in open_tile):
        newBg_left = newBg_left.filter(ImageFilter.GaussianBlur(radius=40))
        tile.image = Image.composite(newBg_left, newIm_right, newIm_right)

    elif ((tile.number + i) not in open_tile) and ((tile.number + j)
                                                   in open_tile):
        newBg_right = newBg_right.filter(ImageFilter.GaussianBlur(radius=40))
        tile.image = Image.composite(newBg_right, newIm_left, newIm_left)

    elif ((tile.number + i) in open_tile) and ((tile.number + j) in open_tile):
        tile.image = Image.composite(newIm_right, newIm_left, newIm_left)

    i = i + 1
    j = j + 1

final_image = join(img_tiles)

unique_name = False
while unique_name == False:
    filename = uuid.uuid4()
    final_filename = str(filename) + '.png'

    if os.path.isfile(final_filename) == False:
        unique_name = True

final_image.save(final_filename)
os.remove(final_bgname)
Esempio n. 29
0
#!/usr/bin/env python
# coding: utf-8

# In[4]:

import image_slicer
#image_slicer.slice('kp.jpg', 9)

# In[6]:

from image_slicer import join
tiles = image_slicer.slice('kp.jpg', 9000, save=True)

# In[7]:

image = join(tiles)
image.save('kp-join.jpg')

# In[ ]:
Esempio n. 30
0
        #yellow means destination is to the south
        if cv2.countNonZero(yellowmask) > 0:
            arr[i] = 2
        #blue means destination is to the left
        if cv2.countNonZero(bluemask) > 0:
            arr[i] = 4

        #pink means destination is to the north
        if cv2.countNonZero(pinkmask) > 0:
            arr[i] = 3
        #green means destination is to the right
        if cv2.countNonZero(greenmask) > 0:
            arr[i] = 5
        # Code to add name of destination
        if arr[i] == 2 or arr[i] == 3 or arr[i] == 4 or arr[i] == 5:
            tile.image = Image.open(r"animate.png")
            image_src = join(tiles)
            image_src.show()
            dest = easygui.enterbox("Enter the name of the destination node")
            tile.image = stiles[i].image
            # d[i]=dest
            # dest=k
            df.loc[k] = [dest, 19 - (i // 20), i % 20]
            k += 1

    i = i + 1

graph = np.reshape(arr, (20, 20))
print(graph)
print(df)
df.to_csv("Nodes.csv", index=False)
Esempio n. 31
0
import image_slicer
from PIL import Image
import cv2
import numpy


#work1
images = image_slicer.slice(r"C:\Users\shado\Desktop\AI_Severstal_Trash\original.jpg", 5, save=False)

for v in images:
    v.image = Image.fromarray(cv2.rectangle(numpy.array(v.image), (50, 50), (300, 100), (0, 255, 255), 10))
    # cv2.imshow("Image", numpy.array(v.image))
    # cv2.waitKey(0)

print(images)
image_slicer.join(images)
cv2.imshow("Image", numpy.array(image_slicer.join(images)))
cv2.waitKey(0)


#work2