Explorar o código

Grijswaarde afbeelding klasse aangemaakt met de volgende features:
- RGB afbeeldingen worden omgezet naar grijswaarden
- Mogelijkheid om klasse instantie direct te indexen: image[y,x]
- Mogelijkheid om op klasse instantie te itereren: for pixel in image: ...
- Direct tonen van afbeelding: image.show()
- Croppen van afbeelding via een Rectangle(x, y, width, height)

Gijs van der Voort %!s(int64=14) %!d(string=hai) anos
pai
achega
84d501fa22
Modificáronse 2 ficheiros con 56 adicións e 0 borrados
  1. 49 0
      src/GrayscaleImage.py
  2. 7 0
      src/Rectangle.py

+ 49 - 0
src/GrayscaleImage.py

@@ -0,0 +1,49 @@
+from pylab import *
+
+class GrayscaleImage:
+
+    def __init__(self, image_path = None, data = None):
+        if image_path != None:
+            self.data = imread(image_path)
+            self.convert_to_grayscale()
+        elif data != None:
+            self.data = data
+    
+    def __iter__(self):
+        self.i_x = -1
+        self.i_y = 0
+        return self
+            
+    def next(self):
+        self.i_x += 1
+        if self.i_x  == self.width:
+            self.i_x = 0
+            self.i_y += 1
+        elif self.i_y == self.height:
+            raise StopIteration
+        else:
+            return self[self.i_y, self.i_x]
+            
+    def __getitem__(self, position):
+        return self.data[position]
+        
+    def convert_to_grayscale(self):
+        self.data = self.data.sum(axis=2) / 3
+        
+    def crop(self, rectangle):
+        self.data = self.data[rectangle.y : rectangle.y + rectangle.height, 
+                              rectangle.x : rectangle.x + rectangle.width]
+                              
+    def show(self):
+        imshow(self.data, cmap="gray")
+        show()
+    
+    def get_width(self):
+        return len(self.data[0])
+        
+    def get_height(self):
+        return len(self.data)
+    
+    width = property(get_width)
+    height = property(get_height)
+    

+ 7 - 0
src/Rectangle.py

@@ -0,0 +1,7 @@
+class Rectangle:
+
+    def __init__(self, x, y, width, height):
+        self.x = x;
+        self.y = y;
+        self.width = width;
+        self.height = height;