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

Add A2

parents
No related branches found
No related tags found
No related merge requests found
.DS_Store
.idea/
__pycache__
A2/GUI.py 0 → 100644
from tkinter import Label, Tk, Button, Entry, IntVar
from tkinter.filedialog import askopenfilename
from tokenize import String
from PIL import ImageTk, Image
from orb import ORB
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.jpeg'
self.edit_path = './images/result.jpeg'
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()
# 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.k_value = IntVar(self.master)
self.k_value.set(1)
self.b_menu = Entry(self.master, textvariable=self.k_value)
# Layout
self.file_dialog.grid(row=0, column=0)
self.doit.grid(row=0, column=1)
self.b_menu.grid(row=0, column=2)
self.original_image_label.grid(row=1, column=0)
self.filtered_image_label.grid(row=1, 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, 1, 0)
self.k_value.set(1)
self._update_label_image(self.filtered_image_label, new_image, 1, 2)
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, 1, 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 K: '
+ str(self.k_value.get()))
ORB(
self.image_path, self.edit_path, self.k_value.get()
).get_keypoints()
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.
"""
root = Tk()
root.resizable(False, False)
my_gui = GUI(root)
root.mainloop()
# Histograms
| Histogram
:---------------------------------------------:|
![](./images/chalsea/Kadse.jpeg) |
![](./images/chalsea/H1.jpeg) |
![](./images/chalsea/H5.jpeg) |
![](./images/chalsea/H10.jpeg) |
![](./images/chalsea/H15.jpeg) |
![](./images/chalsea/H20.jpeg) |
Es lässt sich erkenne, dass beide Histograme ähnlich arbeiten.
Mit der Partitionierung ist es möglich zu erkennen in welchen Intervall sich Farben häufen.
Mit dem einfachen Histogram ist es nur möglich das gesamte Sprektrum zu begutachten.
Durch die Partitionierung können so Intervalle festgelegt werden in denen sich besonders viele Farben/Feature häufen.
\ No newline at end of file
A2/images/chalsea/Kadse.jpeg

47 KiB

A2/images/martian/martian.jpg

202 KiB

A2/images/original.jpeg

39.4 KiB

A2/images/result.jpeg

363 KiB

import math
from tokenize import String
from typing import List
import cv2 as cv
import imageio
import matplotlib.pyplot as plt
import numpy as np
class ORB(object):
def __init__(self, origin_path: String, edit_path: String, k: int = 0):
"""
This class is the editor which edits a given image and stores a new one.
:param origin_path: The original image which should be edited.
:param edit_path: The edited image which should be stored.
:param k: Is used fr K-Means.
"""
self.image_path = origin_path
self.edit_path = edit_path
self.k = k
@staticmethod
def euclidean(vector1: List, vector2: List) -> float:
"""
This method calculates the euclidean distance.
:param vector1: Vector as list
:param vector2: Vector as list
:return: Euclidean distance between vector1 and vector2.
"""
dist = [(a - b) ** 2 for a, b in zip(vector1, vector2)]
dist = math.sqrt(sum(dist))
return dist
def pairwise_arg_min(self, X: List, Y: List) -> np.ndarray:
"""
This method returns a list of all pairwise distances from X to Y.
:param X: Vector with features
:param Y: Centroids
:return: List of all pairwise distances from X to Y.
"""
return np.asarray([np.argmin([self.euclidean(x, y) for y in Y]) for x in X])
def find_clusters(self, X, n_clusters, rseed=2):
# 1. Randomly choose clusters
rng = np.random.RandomState(rseed)
i = rng.permutation(X.shape[0])[:n_clusters]
centers = X[i]
while True:
# 2a. Assign labels based on closest center
labels = self.pairwise_arg_min(X, centers)
# 2b. Find new centers from means of points
new_centers = np.array([X[labels == i].mean(0)
for i in range(n_clusters)])
# 2c. Check for convergence
if np.all(centers == new_centers):
break
centers = new_centers
return centers, labels
def get_keypoints(self) -> None:
"""
This method does K-Means with the ORB Keypoints.
:return: None
"""
img = imageio.imread(uri=self.image_path)
plt.imshow(img)
# Initiate ORB detector
orb = cv.ORB_create(nfeatures=1000, scoreType=cv.ORB_FAST_SCORE)
# find the keypoints with ORB
kp = orb.detect(img, None)
# compute the descriptors with ORB
kp, des = orb.compute(img, kp)
key_points = [k.pt for k in kp]
X = np.array([list(x) for x in key_points])
centers, labels = self.find_clusters(X, self.k)
plt.scatter(X[:, 0], X[:, 1], marker='.', s=1, c=labels, cmap='viridis')
plt.scatter(centers[:, 0], centers[:, 1], marker='+', color='red')
plt.axis('off')
plt.savefig(self.edit_path, dpi=300, bbox_inches='tight')
plt.close()
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread('./images/martian/martian.jpg', 0)
# Initiate ORB detector
orb = cv.ORB_create()
# find the keypoints with ORB
kp = orb.detect(img, None)
# compute the descriptors with ORB
kp, des = orb.compute(img, kp)
key_points = [k.pt for k in kp]
# draw only keypoints location,not size and orientation
img2 = cv.drawKeypoints(img, kp, None, color=(0, 255, 0), flags=0)
# plt.scatter(*zip(*key_points))
plt.imshow(img2)
# plt.show()
from sklearn.metrics import pairwise_distances_argmin
def find_clusters(X, n_clusters, rseed=2):
# 1. Randomly choose clusters
rng = np.random.RandomState(rseed)
i = rng.permutation(X.shape[0])[:n_clusters]
centers = X[i]
while True:
# 2a. Assign labels based on closest center
labels = pairwise_distances_argmin(X, centers)
# 2b. Find new centers from means of points
new_centers = np.array([X[labels == i].mean(0)
for i in range(n_clusters)])
# 2c. Check for convergence
if np.all(centers == new_centers):
break
centers = new_centers
return centers, labels
X = np.array([list(x) for x in key_points])
centers, labels = find_clusters(X, 3)
plt.scatter(X[:, 0], X[:, 1], marker='o', c=labels,
s=50, cmap='viridis')
plt.scatter(centers[:, 0], centers[:, 1], marker='+', color='red')
plt.show()
imageio==2.5.0
Pillow==6.0.0
scikit-image==0.15.0
numpy == 1.16.2
scipy == 1.2.1
scikit-learn==0.21.0
opencv-python==4.1.0.25
opencv-contrib-python==4.1.0.25
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment