Skip to content
Snippets Groups Projects
Commit c016c870 authored by Marc Feger's avatar Marc Feger
Browse files

Init commit

parents
No related branches found
No related tags found
No related merge requests found
Showing
with 591 additions and 0 deletions
.DS_Store
.idea/
__pycache__
\ No newline at end of file
A2/GUI.py 0 → 100644
import sys
from tkinter import Label, Tk, Button, Entry, IntVar, DoubleVar
from tkinter.filedialog import askopenfilename
from tokenize import String
from PIL import ImageTk, Image
from Interface import Interface
class GUI(object):
def __init__(self, master):
"""
This class defines the GUI as one.
:param master: The Tk root.
"""
self.master = master
self.master.title('Filter')
self.image_label_width = 500
self.image_label_height = 500
# Images
self.image_path = './images/original.jpg'
self.edit_path = './images/result.jpg'
self.image = self.read_image(self.image_path)
# Labels
self.original_image_label = Label(self.master, image=self.image)
self.original_image_label.pack()
self.filtered_image_label = Label(self.master, image=self.image)
self.filtered_image_label.pack()
self.bins_label = Label(self.master, text='Bins')
self.bins_label.pack()
self.threshold_label = Label(self.master, text='Threshold')
self.threshold_label.pack()
self.alpha_label = Label(self.master, text='Alpha')
self.alpha_label.pack()
# Buttons
self.file_dialog = Button(master, text='Choose', command=lambda: self.set_new_file())
self.doit = Button(master, text='Do it', command=lambda: self.change_filter())
# Entry
self.bins_value = IntVar(self.master)
self.bins_value.set(2)
self.bins_menu = Entry(self.master, textvariable=self.bins_value)
self.threshold_value = IntVar(self.master)
self.threshold_value.set(1)
self.threshold_menu = Entry(self.master, textvariable=self.threshold_value)
self.alpha_value = DoubleVar(self.master)
self.alpha_value.set(1)
self.alpha_menu = Entry(self.master, textvariable=self.alpha_value)
# Layout
self.file_dialog.grid(row=1, column=1)
self.doit.grid(row=2, column=1)
self.bins_label.grid(row=3, column=1)
self.bins_menu.grid(row=4, column=1)
self.threshold_label.grid(row=5, column=1)
self.threshold_menu.grid(row=6, column=1)
self.alpha_label.grid(row=7, column=1)
self.alpha_menu.grid(row=8, column=1)
self.original_image_label.grid(row=0, column=0)
self.filtered_image_label.grid(row=0, column=2)
def read_image(self, path: String) -> ImageTk.PhotoImage:
"""
This reads an image from a given path and resize it.
:param path: The path to the image.
:return: A image to be used in the frontend
"""
return ImageTk.PhotoImage(
Image.open(path).resize(
(self.image_label_width, self.image_label_height),
Image.ANTIALIAS
)
)
def _update_label_image(self, label: Label, new_image, row: int, column: int) -> None:
"""
This method updates to label with a new image.
:param label: The reference to the label which should be changes.
:param new_image: The reference to the new image.
:param row: Row in the GUI.
:param column: Column in the GUI.
:return: None
"""
label.destroy()
label = Label(self.master, image=new_image)
label.image = new_image
label.pack()
label.grid(row=row, column=column)
def set_new_file(self, *args) -> None:
"""
This sets the new file and refreshed the paths as well with the lables.
:return: None
"""
self.image_path: String = askopenfilename(initialdir='/', title='Select file')
new_image = self.read_image(self.image_path)
self._update_label_image(self.original_image_label, new_image, 0, 0)
self._update_label_image(self.filtered_image_label, new_image, 0, 2)
self.bins_value.set(2)
self.threshold_value.set(1)
self.alpha_value.set(1)
def change_filter(self, *args) -> None:
"""
This changes the filter and updates the label for the edited images.
:param args: Arguments of the listener.
:return: None
"""
self.edit_image()
edited_image = self.read_image(self.edit_path)
self._update_label_image(self.filtered_image_label, edited_image, 0, 2)
def edit_image(self) -> None:
"""
This method edits a given image and saves the edited one.
:return: None
"""
print('From: ' + self.image_path +
' to ' + self.edit_path +
' and Bins: ' + str(self.bins_value.get()) +
' and Threshold: ' + str(self.threshold_value.get()) +
' and Alpha: ' + str(self.alpha_value.get())
)
Interface(image_path=self.image_path,
edit_path=self.edit_path,
bins=self.bins_value.get(),
threshold=self.threshold_value.get(),
alpha=self.alpha_value.get()).doit()
if __name__ == '__main__':
"""
This program is for editing images with ORB keypoints.
Those keypoints are then been grouped with k-means.
Preparation:
Make sure you have already installed all packages by running:
$ pip3 install -r requirements.txt
To use the program run:
$ python3 GUI.py
Notice: The edited image will be saved in ./images/result.py. Each new iteration will overwrite this image. This may
take a while.
"""
sys.setrecursionlimit(2000000000)
root = Tk()
root.resizable(False, False)
my_gui = GUI(root)
root.mainloop()
# Program to count islands in boolean 2D matrix
import copy
import numpy as np
from KEYS import KEYS
class Graph(object):
def __init__(self, row, col, g, bins, threshold) -> None:
self.ROW = row
self.COL = col
self.graph = g
self.connected_components = [[None for _ in range(col)] for _ in range(row)]
self.bins = bins
self.threshold = threshold
def isSafe(self, i, j, visited, g):
return 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and g[i][j]
def DFS(self, i, j, visited, g):
rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1]
colNbr = [-1, 0, 1, -1, 1, -1, 0, 1]
visited[i][j] = True
for k in range(8):
if self.isSafe(i + rowNbr[k], j + colNbr[k], visited, g):
self.DFS(i + rowNbr[k], j + colNbr[k], visited, g)
def label_connected_components(self, visited, label, count):
for x in range(self.ROW):
for y in range(self.COL):
if self.connected_components[x][y] is None and visited[x][y] is True:
self.connected_components[x][y] = {
KEYS.LABEL.name: count, # list(string.ascii_lowercase)[count],
KEYS.COLOR.name: label
}
def detect_connected_components(self):
visited = [[False for _ in range(self.COL)] for _ in range(self.ROW)]
count = 0
for numb in range(1, self.bins + 1):
g = self.binary_matrix(numb, self.graph, self.ROW, self.COL)
for i in range(self.ROW):
for j in range(self.COL):
if visited[i][j] is False and g[i][j] == 1:
self.DFS(i, j, visited, g)
self.label_connected_components(visited, numb, count)
count += 1
print(np.array(visited))
return count
def binary_matrix(self, number, g, r, c):
adjacency_matrix = copy.deepcopy(g)
for i in range(r):
for j in range(c):
adjacency_matrix[i][j] = 1 if adjacency_matrix[i][j] == number else 0
return adjacency_matrix
def ccv(self):
results = {}
for x in range(self.ROW):
for y in range(self.COL):
label = self.connected_components[x][y][KEYS.LABEL.name]
color = self.connected_components[x][y][KEYS.COLOR.name]
if label not in results:
results[label] = {
KEYS.COUNT.name: 1,
KEYS.COLOR.name: color,
KEYS.PIXELS.name: [(x, y)]
}
else:
results[label][KEYS.COUNT.name] += 1
results[label][KEYS.PIXELS.name] += [(x, y)]
vector = {}
for i in range(1, self.bins + 1):
vector[i] = {
KEYS.ALPHA.name: 0,
KEYS.BETA.name: 0
}
for result in results:
color = results[result][KEYS.COLOR.name]
if results[result][KEYS.COUNT.name] >= self.threshold:
vector[color][KEYS.ALPHA.name] += results[result][KEYS.COUNT.name]
else:
vector[color][KEYS.BETA.name] += results[result][KEYS.COUNT.name]
return results, vector
import copy
from tokenize import String
import numpy as np
from matplotlib import pyplot as plt
from skimage import io
from Graph import Graph
from KEYS import KEYS
class Interface(object):
def __init__(self, image_path: String, edit_path: String, bins: int, threshold: int, alpha: float) -> None:
self.image_path = image_path
self.edit_path = edit_path
self.bins = bins
self.threshold = threshold
self.alpha = alpha
def rgb2gray(self, rgb):
return np.dot(rgb[..., :3], [0.2989, 0.5870, 0.1140])
def visualize(self, img, results, threshold, alpha):
rows = len(img)
columns = len(img[0, 0:])
above = copy.deepcopy(img)
# above[i, j, :] = [0, 255, 0]
coherent_pixels = []
for result in results:
if results[result][KEYS.COUNT.name] >= threshold:
coherent_pixels += results[result][KEYS.PIXELS.name]
print(len(coherent_pixels))
for x, y in coherent_pixels:
above[x, y, :] = [0, 255, 0]
plt.axis('off')
plt.imshow(img)
plt.imshow(above, interpolation='none', alpha=alpha)
plt.savefig(fname=self.edit_path, dpi=300, bbox_inches='tight')
plt.close()
# plt.show()
def doit(self):
img = np.array(io.imread(self.image_path))
gray = np.array(np.round(np.divide(self.rgb2gray(img), 256 / (self.bins - 1))).astype(np.int))
gray = np.array(np.add(gray, 1))
row = len(gray)
col = len(gray[0])
g = Graph(row, col, gray, self.bins, self.threshold)
print("Connected components: ")
g.detect_connected_components()
# print(g.connected_components)
res, vec = g.ccv()
print(res)
print(vec)
self.visualize(img, res, self.threshold, self.alpha)
from enum import Enum
class KEYS(Enum):
LABEL = 'label'
COLOR = 'color'
COUNT = 'count'
ALPHA = 'alpha'
BETA = 'beta'
PIXELS = 'pixels'
A2/images/astronauts/Catherine-Coleman.jpg

23.9 KiB

A2/images/astronauts/Donald_Thomas.jpg

13.7 KiB

A2/images/astronauts/Eileen-Collins-2.jpg

46.4 KiB

A2/images/astronauts/Eileen-Collins.jpg

10.2 KiB

A2/images/astronauts/James_Halsell.jpg

15.8 KiB

A2/images/astronauts/Kathryn_P._Hire.jpg

17.5 KiB

A2/images/astronauts/Maurizio-Cheli.jpg

11.9 KiB

A2/images/original.jpg

10.2 KiB

A2/images/result.jpg

403 KiB

File added
File added
foo.py 0 → 100644
# Program to count islands in boolean 2D matrix
import copy
import string
import numpy as np
class Graph:
def __init__(self, row, col, g):
self.ROW = row
self.COL = col
self.graph = g
self.islands = [[None for _ in range(col)] for _ in range(row)]
def isSafe(self, i, j, visited, g):
return 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and g[i][j]
def DFS(self, i, j, visited, g):
rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1]
colNbr = [-1, 0, 1, -1, 1, -1, 0, 1]
visited[i][j] = True
for k in range(8):
if self.isSafe(i + rowNbr[k], j + colNbr[k], visited, g):
self.DFS(i + rowNbr[k], j + colNbr[k], visited, g)
def countIslands(self):
visited = [[False for _ in range(self.COL)] for _ in range(self.ROW)]
count = 0
for numb in [1, 2, 3]:
g = self.highlight(numb, self.graph, self.ROW, self.COL)
print(np.array(g))
for i in range(self.ROW):
for j in range(self.COL):
if visited[i][j] is False and g[i][j] == 1:
self.DFS(i, j, visited, g)
for x in range(self.ROW):
for y in range(self.COL):
if self.islands[x][y] is None and visited[x][y] is True:
self.islands[x][y] = (list(string.ascii_lowercase)[count], numb)
count += 1
print(np.array(self.islands))
return count
def highlight(self, number, g, r, c):
adjacency_matrix = copy.deepcopy(g)
for i in range(r):
for j in range(c):
adjacency_matrix[i][j] = 1 if adjacency_matrix[i][j] == number else 0
return adjacency_matrix
def bins(self):
bins = {}
for x in range(self.ROW):
for y in range(self.COL):
if self.islands[x][y] not in bins:
bins[self.islands[x][y]] = 1
else:
bins[self.islands[x][y]] += 1
return bins
if __name__ == '__main__':
graph = [[2, 1, 2, 2, 1, 1],
[2, 2, 1, 2, 1, 1],
[2, 1, 3, 2, 1, 1],
[2, 2, 2, 1, 1, 2],
[2, 2, 1, 1, 2, 2],
[2, 2, 1, 1, 2, 2]]
row = len(graph)
col = len(graph[0])
g = Graph(row, col, graph)
print("Number of islands is:")
g.countIslands()
print(g.bins())
imageio==2.5.0
Pillow==6.0.0
scikit-image==0.15.0
numpy == 1.16.2
opencv-python==4.1.0.25
opencv-contrib-python==4.1.0.25
\ No newline at end of file
test.py 0 → 100644
# Program to count islands in boolean 2D matrix
import copy
import string
import sys
import numpy as np
from enum import Enum
from skimage import io
from matplotlib import pyplot as plt
class KEYS(Enum):
LABEL = 'label'
COLOR = 'color'
COUNT = 'count'
ALPHA = 'alpha'
BETA = 'beta'
PIXELS = 'pixels'
class Graph:
def __init__(self, row, col, g, bins, threshold):
self.ROW = row
self.COL = col
self.graph = g
self.connected_components = [[None for _ in range(col)] for _ in range(row)]
self.bins = bins
self.threshold = threshold
def isSafe(self, i, j, visited, g):
return 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and g[i][j]
def DFS(self, i, j, visited, g):
rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1]
colNbr = [-1, 0, 1, -1, 1, -1, 0, 1]
visited[i][j] = True
for k in range(8):
if self.isSafe(i + rowNbr[k], j + colNbr[k], visited, g):
self.DFS(i + rowNbr[k], j + colNbr[k], visited, g)
def label_connected_components(self, visited, label, count):
for x in range(self.ROW):
for y in range(self.COL):
if self.connected_components[x][y] is None and visited[x][y] is True:
self.connected_components[x][y] = {
KEYS.LABEL.name: count, # list(string.ascii_lowercase)[count],
KEYS.COLOR.name: label
}
def detect_connected_components(self):
visited = [[False for _ in range(self.COL)] for _ in range(self.ROW)]
count = 0
for numb in range(1, self.bins + 1):
g = self.binary_matrix(numb, self.graph, self.ROW, self.COL)
for i in range(self.ROW):
for j in range(self.COL):
if visited[i][j] is False and g[i][j] == 1:
self.DFS(i, j, visited, g)
self.label_connected_components(visited, numb, count)
count += 1
print(np.array(visited))
return count
def binary_matrix(self, number, g, r, c):
adjacency_matrix = copy.deepcopy(g)
for i in range(r):
for j in range(c):
adjacency_matrix[i][j] = 1 if adjacency_matrix[i][j] == number else 0
return adjacency_matrix
def ccv(self):
results = {}
for x in range(self.ROW):
for y in range(self.COL):
label = self.connected_components[x][y][KEYS.LABEL.name]
color = self.connected_components[x][y][KEYS.COLOR.name]
if label not in results:
results[label] = {
KEYS.COUNT.name: 1,
KEYS.COLOR.name: color,
KEYS.PIXELS.name: [(x, y)]
}
else:
results[label][KEYS.COUNT.name] += 1
results[label][KEYS.PIXELS.name] += [(x, y)]
vector = {}
for i in range(1, self.bins + 1):
vector[i] = {
KEYS.ALPHA.name: 0,
KEYS.BETA.name: 0
}
for result in results:
color = results[result][KEYS.COLOR.name]
if results[result][KEYS.COUNT.name] >= self.threshold:
vector[color][KEYS.ALPHA.name] += results[result][KEYS.COUNT.name]
else:
vector[color][KEYS.BETA.name] += results[result][KEYS.COUNT.name]
return results, vector
def rgb2gray(rgb):
return np.dot(rgb[..., :3], [0.2989, 0.5870, 0.1140])
def visualize(img, results, threshold, alpha):
rows = len(img)
columns = len(img[0, 0:])
above = copy.deepcopy(img)
# above[i, j, :] = [0, 255, 0]
coherent_pixels = []
for result in results:
if results[result][KEYS.COUNT.name] >= threshold:
coherent_pixels += results[result][KEYS.PIXELS.name]
print(len(coherent_pixels))
for x, y in coherent_pixels:
above[x, y, :] = [0, 255, 0]
plt.imshow(img)
plt.imshow(above, interpolation='none', alpha=alpha)
plt.show()
if __name__ == '__main__':
sys.setrecursionlimit(2000000000)
print(sys.getrecursionlimit())
graph = np.array([[2, 1, 2, 2, 1, 1],
[2, 2, 1, 2, 1, 1],
[2, 1, 3, 2, 1, 1],
[2, 2, 2, 1, 1, 2],
[2, 2, 1, 1, 2, 2],
[2, 2, 1, 1, 2, 2]])
b = 3
t = 50
a = 0.5
img = np.array(io.imread('./A2/images/astronauts/Eileen-Collins-2.jpg')) # [:100, :100]
gray = np.array(np.round(np.divide(rgb2gray(img), 256 / (b - 1))).astype(np.int))
gray = np.array(np.add(gray, 1))
print(type(gray))
print(np.array(gray))
row = len(gray)
col = len(gray[0])
g = Graph(row, col, gray, b, t)
print("Connected components: ")
g.detect_connected_components()
# print(g.connected_components)
res, vec = g.ccv()
print(res)
print(vec)
visualize(img, res, t, a)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment