Friday, October 13, 2023

OpenCV and Image Processing - Resize, Crop and Rotate an Image

Python is an excellent language to support object-oriented programming, this post will start to use object-oriented techniques to write the codes. We will create classes to include properties and functions, then instantiate the classes and invoke their functions.

Now create a class called ImageProcessing, and define three functions inside, resize(), rotate() and crop(). When a class is created it always has a built-in __init__() function, which is always executed when the class is instantiated. It’s used to assign initial values to the properties or other operations that are necessary when the object is created. Here we set the window_name and image_name properties inside __init__() function.

1 import cv2

2

3 class ImageProcessing(object):

4 def __init__(self, window_name, image_name):

5 self.window_name = window_name 

6 self.image_name = image_name

7 self.image = cv2.imread(self.image_name)

8

9 def show(self, title=None, image=None):

10 if image is None:

11 image = self.image

12 if title is None:

13 title = self.window_name

14 cv2.imshow(title, image)


To continue, add three functions, resize(), crop() and rotate(), to the class:

16 def resize(self, percent, image=None):

17 if image is None:

18 image = self.image

19 width = int(image.shape[1]*percent/100)

20 height = int(image.shape[0]*percent/100)

21 resized_image = cv2.resize(image, (width, height) )

22 return resized_image

23

24 def crop(self,pt_first,pt_second,image=None):

25 if image is None:

26 image = self.image

27 # top-left point

x_tl, y_tl = pt_first

28 # bottom-right point

x_br, y_br = pt_second

29 # swap x value if opposite

if x_br < x_tl:

30 x_br, x_tl = x_tl, x_br

31 # swap y value if opposite

if y_br < y_tl:

32 y_br, y_tl = y_tl, y_br

33 cropped_image=image[y_tl:y_br,x_tl:x_br]

34 return cropped_image

35

36 def rotate(self,angle,image=None,scale=1.0):

37 if image is None:

38 image = self.image

39 (h, w) = image.shape[:2]

40 center = (w / 2, h / 2)

41 rot_mat = cv2.getRotationMatrix2D(center, angle, scale)

42 rotated_image = cv2.warpAffine(image, rot_mat, (w, h))

43 return rotated_image


The class definition for ImageProcessing is done for now, more functions will be added later.

Share:

0 comments:

Post a Comment