├── .gitignore ├── macros.py ├── pressed_key_lookup.py ├── helping_doc.md ├── image.py ├── move.py ├── main.py ├── helping_functions.py ├── drawing.py ├── selectRegionClass.py ├── marquee.py ├── layers.py ├── selection.py ├── input_output.py ├── lasso.py └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | # Python extra files 2 | /.vscode 3 | /__pycache__ 4 | /.pylintrc 5 | 6 | # All images in the main directory 7 | /*.png 8 | /*.jpg 9 | /*.jpeg 10 | /*.svg 11 | -------------------------------------------------------------------------------- /macros.py: -------------------------------------------------------------------------------- 1 | # Default size of new image 2 | DEFAULT_CANVAS_HEIGHT = 750 3 | DEFAULT_CANVAS_WIDTH = 1500 4 | 5 | 6 | # The default title of the mian canvas 7 | DEFAULT_CANVAS_TITLE = "Main" 8 | 9 | 10 | # The size of the grid box of the base layer 11 | GRID_BOX_SIZE = 5 12 | -------------------------------------------------------------------------------- /pressed_key_lookup.py: -------------------------------------------------------------------------------- 1 | # 128 ASCII values available 2 | action = [] 3 | action_statements = [] 4 | 5 | action.append("EXIT") 6 | action_statements.append("0 : EXIT code") 7 | 8 | action.append("ADD_LAYER") 9 | action_statements.append("1 : Add new Layer") 10 | 11 | action.append("SHOW_SELECTED_LAYERS") 12 | action_statements.append("2 : Show specific layers") 13 | 14 | action.append("LAYER_OPERATIONS") 15 | action_statements.append("3 : Perform layer operations (Rearrange, Delete, Merge, Rename, Duplicate Layers)") 16 | 17 | action.append("MOVE_TOOL") 18 | action_statements.append("4 : Move Tool") 19 | 20 | action.append("MARQUEE_TOOL") 21 | action_statements.append("5 : Marquee Tool") 22 | 23 | action.append("LASSO_TOOL") 24 | action_statements.append("6 : Lasso Tool") 25 | 26 | action.append("SELECTION_TOOL") 27 | action_statements.append("7 : Selection Tool") 28 | -------------------------------------------------------------------------------- /helping_doc.md: -------------------------------------------------------------------------------- 1 | ### Mouse click events 2 | 3 | * EVENT_FLAG_ALTKEY : - 4 | * EVENT_FLAG_CTRLKEY : With Right Button Double Click 5 | * EVENT_FLAG_LBUTTON : With Mouse Left Button Press(Down) 6 | * EVENT_FLAG_MBUTTON : With Mouse Left Button Release(Up) 7 | * EVENT_FLAG_RBUTTON : With Mouse Right Button Press(Down) 8 | * EVENT_FLAG_SHIFTKEY : - 9 | * EVENT_LBUTTONDBLCLK : Mouse Left Button Double Click 10 | * EVENT_LBUTTONDOWN : Mouse Left Button Press(Down) 11 | * EVENT_LBUTTONUP : Mouse Left Button Release(Up) 12 | * EVENT_MBUTTONDBLCLK : Mouse Wheel Button Double Click 13 | * EVENT_MBUTTONDOWN : Mouse Wheel Button Press(Down) 14 | * EVENT_MBUTTONUP : Mouse Wheel Button Release(Up) 15 | * EVENT_MOUSEHWHEEL : - 16 | * EVENT_MOUSEMOVE : Mouse Moving 17 | * EVENT_MOUSEWHEEL : Mouse wheel scrolled up or down 18 | * EVENT_RBUTTONDBLCLK : Mouse Right Button double click 19 | * EVENT_RBUTTONDOWN : Mouse Right Button press(down) 20 | * EVENT_RBUTTONUP : Mouse Right Button release(up) 21 | 22 | [Official documentation link.](http://115.28.130.42/opencv3.1/d7/dfc/group__highgui.html#gaab4dc057947f70058c80626c9f1c25ce) 23 | 24 | 25 | 26 | ### ASCII Chart 27 | 28 | [Link to ASCII Chart.](http://www.physics.udel.edu/~watson/scen103/ascii.html) -------------------------------------------------------------------------------- /image.py: -------------------------------------------------------------------------------- 1 | import os 2 | import cv2 3 | import numpy as np 4 | 5 | import macros as m 6 | 7 | 8 | # Adds alpha channel to the image 9 | def AddAlphaChannel(Image, mask=None): 10 | if mask is None: # If mask is not provided 11 | MaskImage = np.ones((Image.shape[:2]), dtype=np.uint8) * 255 12 | 13 | else: # If mask is provided 14 | Height_Image, Width_Image = Image.shape[:2] 15 | Height_Mask, Width_Mask = mask.shape[:2] 16 | 17 | # Checking the size of mask 18 | if Height_Image == Height_Mask and Width_Image == Width_Mask: 19 | MaskImage = mask 20 | else: 21 | MaskImage = np.ones((Image.shape[:2]), dtype=np.uint8) * 255 22 | 23 | # Adding the alpha channel to the image 24 | b, g, r = cv2.split(Image) 25 | Image = cv2.merge((b, g, r, MaskImage)) 26 | 27 | return Image 28 | 29 | 30 | # Corrects the iamge dimentions. 31 | # The image should be 4 channeled 32 | def CorrectImage(Image): 33 | Channels = Image.shape[2] 34 | 35 | if Channels == 4: # If image is 4-channeled - do nothing 36 | return Image 37 | 38 | elif Channels == 3: # If image is 3-channeled - add alpha channel 39 | Image = AddAlphaChannel(Image) 40 | 41 | elif Channels == 1: # If image is 1-channeled - convert to bgr and add alpha channel 42 | Image = cv2.cvtColor(Image, cv2.COLOR_GRAY2BGR) 43 | Image = AddAlphaChannel(Image) 44 | 45 | else: 46 | print("The Image cannot be corrected.") 47 | 48 | return Image 49 | 50 | 51 | 52 | # Reads the image from the path given 53 | def ReadImage(ImagePath): 54 | # If the file doesnot exists or is not a file 55 | if not os.path.exists(ImagePath) or not os.path.isfile(ImagePath): 56 | return None 57 | 58 | Image = cv2.imread(ImagePath, cv2.IMREAD_UNCHANGED) 59 | 60 | # If Image is not read properly 61 | if Image is None: 62 | return None 63 | if Image.size == 0: 64 | return None 65 | 66 | # Correcting the image if necessary 67 | Image = CorrectImage(Image) 68 | 69 | return Image 70 | 71 | 72 | def CreateBackgroundImage(Shape): 73 | h, w = Shape 74 | 75 | # Creating the checkered image 76 | background_img = np.ones((h, w, 3), dtype=np.uint8) * 255 77 | 78 | for i in range(0, h, m.GRID_BOX_SIZE): 79 | for j in range(0, w, m.GRID_BOX_SIZE): 80 | if ((i+1) // m.GRID_BOX_SIZE) % 2 == 0: 81 | if ((j+1) // m.GRID_BOX_SIZE) % 2 != 0: 82 | background_img[i:i+m.GRID_BOX_SIZE, j:j + 83 | m.GRID_BOX_SIZE] = [200, 200, 200] 84 | else: 85 | if ((j+1) // m.GRID_BOX_SIZE) % 2 == 0: 86 | background_img[i:i+m.GRID_BOX_SIZE, j:j + 87 | m.GRID_BOX_SIZE] = [200, 200, 200] 88 | 89 | 90 | return background_img 91 | 92 | -------------------------------------------------------------------------------- /move.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | import helping_functions as hf 5 | 6 | 7 | def CallBackFunc_MoveTool(event, x, y, flags, Canvas): 8 | # Taking global params 9 | global moving, movingLayer, im_x, im_y, ii_x, ii_y 10 | 11 | # Starts moving - Left button is pressed down 12 | if event == cv2.EVENT_LBUTTONDOWN: 13 | im_x, im_y = x, y # Setting initial mouse coordinates 14 | 15 | # Finding the moving layer's index 16 | movingLayer = -1 # Dummy value 17 | for i in range(len(Canvas.layers) - 1, -1, -1): # Moving from top to bottom layer 18 | if Canvas.layers[i].IsVisible: 19 | # Layer x, y, and height and width 20 | lx, ly = Canvas.layers[i].Position 21 | lh, lw = Canvas.layers[i].Shape 22 | 23 | if lx <= x < lx + lw and ly <= y < ly + lh: 24 | movingLayer = i 25 | ii_x, ii_y = lx, ly 26 | break 27 | 28 | # Checking if any layer is selected and changing "moving" flag accrodingly. 29 | if movingLayer == -1: # Background layer 30 | moving = False 31 | else: # Start moving selected layer 32 | moving = True 33 | 34 | # Moving the layer while pressing down the mouse left button 35 | elif event == cv2.EVENT_MOUSEMOVE: 36 | if moving: # If a layer is selected and we are moving it 37 | # Changing the image position coordinates according to the difference 38 | # between the initial and the final position of the mouse pointer. 39 | Canvas.layers[movingLayer].Position = [ii_x + x - im_x, ii_y + y - im_y] 40 | 41 | # Stop moving the layer. 42 | elif event == cv2.EVENT_LBUTTONUP: 43 | moving = False 44 | 45 | 46 | def MoveTool(Canvas, window_title): 47 | print("\nPress 'Y' to confirm and exit move tool else keep editing.\n") 48 | 49 | # Clearing mouse buffer data (old mouse data) - this is a bug in OpenCV probably 50 | cv2.namedWindow(window_title) 51 | cv2.setMouseCallback(window_title, hf.EmptyCallBackFunc) 52 | Canvas.Show(Title=window_title) 53 | cv2.waitKey(1) 54 | 55 | # Setting mouse callback 56 | cv2.setMouseCallback(window_title, CallBackFunc_MoveTool, Canvas) 57 | 58 | # Setting some params used in callback function 59 | global moving, movingLayer, im_x, im_y, ii_x, ii_y 60 | moving = False # True when image is selected and being moved 61 | # movingLayer : Index of the layer being moved 62 | # im_x, im_y : Coordinates of the point where mouse left button is pressed 63 | # ii_x, ii_y : Coordinates of the initial position of the image being moved 64 | 65 | 66 | while True: 67 | # Showing canvas 68 | Canvas.Show(Title=window_title) 69 | Key = cv2.waitKey(1) 70 | 71 | if Key == 89 or Key == 121: # If 'Y'/'y' pressed 72 | break 73 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import argparse 4 | 5 | import move 6 | import layers 7 | import macros as m 8 | import input_output 9 | import helping_functions as hf 10 | from pressed_key_lookup import * 11 | 12 | 13 | # Parsing the arguments 14 | def ArgParse(): 15 | global args # Declaring globally to acces it from anywhere. 16 | 17 | # construct the argument parser and parse the arguments 18 | ap = argparse.ArgumentParser() 19 | 20 | ap.add_argument("-img", "--ImagePath", default=None, 21 | help="Path of the image file.") 22 | ap.add_argument("-s", "--Shape", default=None, type=int, nargs=2, 23 | help="Shape of the canvas(integer values only) - [height, width]") 24 | 25 | args = vars(ap.parse_args()) # Converting it to dictionary. 26 | 27 | 28 | 29 | # Printing the action statements for the user to select a tool/feature 30 | def PrintActionStatements(): 31 | print() 32 | print("=================================================================================================================") 33 | for i in action_statements: 34 | print(i) 35 | print("=================================================================================================================") 36 | print() 37 | 38 | 39 | 40 | def TakeOperation_Num(MaxNum): 41 | # Taking input 42 | Operation_Num = input("\nEnter the operation number: ") 43 | 44 | try: # If valid number passed 45 | Operation_Num = Operation_Num.replace(" ", "") 46 | Operation_Num = int(Operation_Num) 47 | if 0 <= Operation_Num < MaxNum: 48 | return Operation_Num 49 | else: 50 | raise ValueError 51 | except: # If invalid number passed 52 | print("\nInvalid operation number entered.") 53 | hf.Sleep() 54 | return None 55 | 56 | 57 | if __name__ == "__main__": 58 | ArgParse() # Parsing command line arguments 59 | 60 | # Reading and initializing the image 61 | Canvas = layers.Initialize(args) 62 | 63 | while True: 64 | # Clearing the screen 65 | hf.Clear() 66 | 67 | # Setting window title 68 | window_title = m.DEFAULT_CANVAS_TITLE 69 | 70 | # Printing action statements for the user 71 | PrintActionStatements() 72 | 73 | # Showing all layers 74 | Canvas.Show() 75 | cv2.waitKey(1) 76 | 77 | # Taking operation number 78 | Operation_Num = TakeOperation_Num(len(action)) 79 | if Operation_Num is None: # Invalid operation number entered 80 | continue 81 | # Getting action string 82 | action_str = action[Operation_Num] 83 | 84 | if action_str is None: # Continue if valid key is not pressed 85 | continue 86 | 87 | elif action_str == "ADD_LAYER": # Add a new layer 88 | input_output.AddNewLayer(Canvas) 89 | 90 | elif action_str == "SHOW_SELECTED_LAYERS": # Show selected layers 91 | input_output.ChooseLayersToShow(Canvas, "Layers selection") 92 | 93 | elif action_str == "LAYER_OPERATIONS": # Rearrange/ Delete/ Merge/ Rename/ Duplicate layers 94 | input_output.LayerOperations(Canvas, "Layer operations") 95 | 96 | elif action_str == "MOVE_TOOL": # Move tool 97 | move.MoveTool(Canvas, window_title) 98 | 99 | elif action_str == "MARQUEE_TOOL": # Marquee tool 100 | input_output.MarqueeTool(Canvas, window_title) 101 | 102 | elif action_str == "LASSO_TOOL": # Lasso Tool 103 | input_output.LassoTool(Canvas, window_title) 104 | 105 | elif action_str == "SELECTION_TOOL": # Selection Tool 106 | input_output.SelectionTool(Canvas, window_title) 107 | 108 | elif action_str == "EXIT": # Exit code 109 | break 110 | 111 | 112 | cv2.destroyAllWindows() 113 | 114 | # Clearing the screen 115 | hf.Clear() -------------------------------------------------------------------------------- /helping_functions.py: -------------------------------------------------------------------------------- 1 | import os 2 | import cv2 3 | import math 4 | import time 5 | import numpy as np 6 | 7 | 8 | def Get_Img_Canvas_ROI(ImageRect, CanvasShape): 9 | # Position of image on the canvas 10 | [i_pos_x, i_pos_y, i_pos_w, i_pos_h] = ImageRect 11 | # Canvas roi (place where image is present on the canvas) 12 | [c_roi_x, c_roi_y, c_roi_w, c_roi_h] = ImageRect 13 | # Coordinates of part of the image present inside the frame 14 | [i_roi_x, i_roi_y, i_roi_w, i_roi_h] = [0, 0, i_pos_w, i_pos_h] 15 | 16 | if i_pos_x < 0: # If image is over left boundary 17 | if abs(i_pos_x) < i_pos_w: # If not completely over left boundary 18 | i_roi_x = -i_pos_x 19 | i_roi_w += i_pos_x 20 | c_roi_x = 0 21 | c_roi_w += i_pos_x 22 | 23 | else: # If completely over left boundary 24 | return None, None 25 | 26 | if i_pos_y < 0: # If image is over top boundary 27 | if abs(i_pos_y) < i_pos_h: # If not completely over top boundary 28 | i_roi_y = -i_pos_y 29 | i_roi_h += i_pos_y 30 | c_roi_y = 0 31 | c_roi_h += i_pos_y 32 | 33 | else: # If completely over top boundary 34 | return None, None 35 | 36 | if i_pos_x + i_pos_w > CanvasShape[1]: # If image is over right boundary 37 | if i_pos_x < CanvasShape[1]: # If not completely over right boundary 38 | c_roi_w = CanvasShape[1] - c_roi_x 39 | i_roi_w -= (i_pos_x + i_pos_w - CanvasShape[1]) 40 | 41 | else: # If completely over right boundary 42 | return None, None 43 | 44 | if i_pos_y + i_pos_h > CanvasShape[0]: # If image is over bottom boundary 45 | if i_pos_y < CanvasShape[0]: # If not completely over bottom boundary 46 | c_roi_h = CanvasShape[0] - c_roi_y 47 | i_roi_h -= (i_pos_y + i_pos_h - CanvasShape[0]) 48 | 49 | else: # If completely over bottom boundary 50 | return None, None 51 | 52 | 53 | return [i_roi_x, i_roi_y, i_roi_w, i_roi_h], [c_roi_x, c_roi_y, c_roi_w, c_roi_h] 54 | 55 | 56 | 57 | def Clear(): 58 | # for windows 59 | if os.name == 'nt': 60 | _ = os.system('cls') 61 | 62 | # for mac and linux(here, os.name is 'posix') 63 | else: 64 | _ = os.system('clear') 65 | 66 | def Sleep(Duration=1): 67 | time.sleep(Duration) 68 | 69 | 70 | def to_xyxy(x, y, w, h): 71 | x2 = x + w - 1 72 | y2 = y + h - 1 73 | 74 | return x2, y2 75 | 76 | 77 | def to_xywh(x1, y1, x2, y2): 78 | w = x2 - x1 + 1 79 | h = y2 - y1 + 1 80 | 81 | return w, h 82 | 83 | 84 | def EmptyCallBackFunc(event, x, y, flags, Canvas): 85 | pass 86 | 87 | 88 | def Correct_xy_While_Selecting(x, y, x_range, y_range): 89 | if x < x_range[0]: 90 | x = x_range[0] 91 | elif x > x_range[1]: 92 | x = x_range[1] 93 | 94 | if y < y_range[0]: 95 | y = y_range[0] 96 | elif y > y_range[1]: 97 | y = y_range[1] 98 | 99 | return x, y 100 | 101 | 102 | def CorrectRectPoints(x1, y1, x2, y2): 103 | return min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2) 104 | 105 | 106 | def Intersection(Rect1, Rect2): 107 | x = max(Rect1[0], Rect2[0]) 108 | y = max(Rect1[1], Rect2[1]) 109 | w = min(Rect1[0] + Rect1[2], Rect2[0] + Rect2[2]) - x 110 | h = min(Rect1[1] + Rect1[3], Rect2[1] + Rect2[3]) - y 111 | 112 | if w < 0 or h < 0: 113 | return None 114 | return [x, y, w, h] 115 | 116 | 117 | def Union(Rect1, Rect2): 118 | x = min(Rect1[0], Rect2[0]) 119 | y = min(Rect1[1], Rect2[1]) 120 | w = max(Rect1[0] + Rect1[2], Rect2[0] + Rect2[2]) - x 121 | h = max(Rect1[1] + Rect1[3], Rect2[1] + Rect2[3]) - y 122 | return (x, y, w, h) 123 | 124 | 125 | def ShiftContour(Contour, ToOrigin=True, ShiftBy=[0, 0], Get_Mask_BB=False): 126 | # Getting the bounding rectangle of the contour. 127 | (x, y, w, h) = cv2.boundingRect(np.array(Contour)) 128 | 129 | # If shift contour to origin, we will have to shift it by the 130 | # value equal to its bounding box's top left coorner coordinate 131 | if ToOrigin: 132 | ShiftBy = [-x, -y] 133 | 134 | # Shifting the contour 135 | ShiftedContour = [] 136 | for i in range(len(Contour)): 137 | try: 138 | ShiftedContour.append([(Contour[i][0] + ShiftBy[0]), (Contour[i][1] + ShiftBy[1])]) 139 | except: 140 | ShiftedContour.append([[(Contour[i][0][0] + ShiftBy[0]), (Contour[i][0][1] + ShiftBy[1])]]) 141 | 142 | 143 | # If bounding box and mask image are asked 144 | if Get_Mask_BB: 145 | # Creating the mask image 146 | MaskImage = np.zeros((h, w, 1), dtype=np.uint8) 147 | cv2.drawContours(MaskImage, [np.array(ShiftedContour)], -1, 255, -1) 148 | 149 | return ShiftedContour, MaskImage, (x, y, w, h) 150 | 151 | # If only shifted contour required 152 | else: 153 | return ShiftedContour 154 | 155 | 156 | def ToRowMajor(x, y, NumOfCols): 157 | return (x + (y * NumOfCols)) 158 | 159 | def RevertRowMajor(RowMajor, NumOfCols): 160 | x = RowMajor % NumOfCols 161 | y = RowMajor // NumOfCols 162 | 163 | return x, y 164 | 165 | 166 | def Distance(pt1, pt2): 167 | return math.sqrt( ((pt2[1] - pt1[1]) ** 2) + ((pt2[0] - pt1[0]) ** 2) ) 168 | 169 | 170 | def RemoveContoursDim(Contours): 171 | ReducedContours = [] 172 | 173 | for Contour in Contours: 174 | ReducedContour = [] 175 | for i in range(len(Contour)): 176 | ReducedContour.append([Contour[i][0][0], Contour[i][0][1]]) 177 | 178 | ReducedContours.append(ReducedContour) 179 | 180 | return ReducedContours 181 | -------------------------------------------------------------------------------- /drawing.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | import helping_functions as hf 5 | 6 | 7 | Len = 6 8 | HorizontalOrientation = -1 9 | VerticalOrientation = -2 10 | 11 | # Drawing horizontal line 12 | def HorLine(Image, x1, x2, y): 13 | # 0 <= x1 <= x2 < Image width 14 | if x1 > x2: 15 | x1, x2 = x2, x1 16 | x1, x2 = max(0, x1), min(x2, Image.shape[1]-1) 17 | 18 | Last_x = x1 # Last x value 19 | isWhite = True # Flag for switching b/w black and white 20 | for x in range(x1 + Len, x2 + 1, Len): 21 | if isWhite: 22 | Image[y, Last_x : x + 1, :] = 255 23 | isWhite = False 24 | else: 25 | Image[y, Last_x : x + 1, :] = 0 26 | isWhite = True 27 | 28 | Last_x = x 29 | 30 | # Drawing the last segment 31 | if isWhite: 32 | Image[y, Last_x : x2 + 1, :] = 255 33 | else: 34 | Image[y, Last_x : x2 + 1, :] = 0 35 | 36 | 37 | # Drawing verticle line 38 | def VerLine(Image, x, y1, y2): 39 | # 0 <= y1 <= y2 < Image height 40 | if y1 > y2: 41 | y1, y2 = y2, y1 42 | y1, y2 = max(0, y1), min(y2, Image.shape[0]-1) 43 | 44 | Last_y = y1 # Last y value 45 | isWhite = True # Flag for switching b/w black and white 46 | for y in range(y1 + Len, y2 + 1, Len): 47 | if isWhite: 48 | Image[Last_y : y + 1, x, :] = 255 49 | isWhite = False 50 | else: 51 | Image[Last_y : y + 1, x, :] = 0 52 | isWhite = True 53 | 54 | Last_y = y 55 | 56 | # Drawing the last segment 57 | if isWhite: 58 | Image[Last_y : y2 + 1, x, :] = 255 59 | else: 60 | Image[Last_y : y2 + 1, x, :] = 0 61 | 62 | 63 | # Gets coordinates of all the points on the line 64 | def GetLinePoints(Pt1, Pt2): 65 | [x, y] = Pt1 # Starting Point 66 | 67 | dist = hf.Distance(Pt1, Pt2) # Line length 68 | 69 | if dist == 0: # If line length is 0, return no points 70 | return [] 71 | 72 | # dx is small increment in x value for each increment of 73 | # y value by dy such that the new point still lies on the line. 74 | # [if (x, y) lies on the line, 75 | # then (x + dx, y + dy) also lies on the line] 76 | dx = (Pt2[0] - Pt1[0]) / dist 77 | dy = (Pt2[1] - Pt1[1]) / dist 78 | 79 | Points = [[x, y]] 80 | 81 | minX = min(Pt1[0], Pt2[0]) 82 | maxX = max(Pt1[0], Pt2[0]) 83 | minY = min(Pt1[1], Pt2[1]) 84 | maxY = max(Pt1[1], Pt2[1]) 85 | 86 | # Loop until the new point lies inside the image 87 | while minX <= x <= maxX and minY <= y <= maxY: 88 | x += dx 89 | y += dy 90 | Pt = [int(x), int(y)] 91 | 92 | if not (Pt[0] == Points[-1][0] and Pt[1] == Points[-1][1]): 93 | Points.append(Pt) 94 | 95 | return Points 96 | 97 | 98 | # Drawing a line at some angle except 0 or 90. 99 | def LineAtAngle(Image, Pt1, Pt2, isDashed): 100 | # Getting the line points 101 | Points = GetLinePoints(Pt1, Pt2) 102 | 103 | if isDashed: 104 | # Drawing dashed line 105 | isWhite = True 106 | for i in range(0, len(Points), Len): 107 | for j in range(i, Len+i): 108 | try: # Index out of range error for j = len(Points) 109 | if isWhite: 110 | Image[Points[j][1]][Points[j][0]] = [255, 255, 255] 111 | else: 112 | Image[Points[j][1]][Points[j][0]] = [0, 0, 0] 113 | except: 114 | pass 115 | 116 | # Switching colour 117 | isWhite = not isWhite 118 | 119 | else: 120 | for Pt in Points: 121 | Image[Pt[1]][Pt[0]] = [127, 127, 127] 122 | # if (Image[Pt[1]][Pt[0]] <= 127).all(): 123 | # Image[Pt[1]][Pt[0]] = [255, 255, 255] 124 | # else: 125 | # Image[Pt[1]][Pt[0]] = [0, 0, 0] 126 | 127 | 128 | # Drawing line (currently only horizontal and verticle lines are supported) 129 | def Line(Image, Pt1, Pt2, Orientation=0): 130 | # Horizontal Line 131 | if Orientation == HorizontalOrientation: 132 | if Pt1[0] > Pt2[0]: 133 | Pt1[0], Pt2[0] = Pt2[0], Pt1[0] 134 | HorLine(Image, min(Pt1[0], Pt2[0]), max(Pt1[0], Pt2[0]), Pt1[1]) 135 | 136 | # Vertical Line 137 | elif Orientation == VerticalOrientation: 138 | if Pt1[1] > Pt2[1]: 139 | Pt1[1], Pt2[1] = Pt2[1], Pt1[1] 140 | VerLine(Image, Pt1[0], min(Pt1[1], Pt2[1]), max(Pt1[1], Pt2[1])) 141 | 142 | # Line at angle 143 | else: 144 | LineAtAngle(Image, Pt1, Pt2, True) 145 | 146 | 147 | # Drawing normal rectangle (sides parallel to axes) 148 | def Rectangle(Image, Pt1, Pt2): 149 | x1 = min(Pt1[0], Pt2[0]) 150 | x2 = max(Pt1[0], Pt2[0]) 151 | y1 = min(Pt1[1], Pt2[1]) 152 | y2 = max(Pt1[1], Pt2[1]) 153 | 154 | if x1 == x2 and y1 == y2: 155 | return 156 | 157 | # Drawing the 4 lines of the rectangle 158 | Line(Image, [x1, y1], [x2, y1], HorizontalOrientation) 159 | Line(Image, [x2, y1], [x2, y2], VerticalOrientation) 160 | Line(Image, [x2, y2], [x1, y2], HorizontalOrientation) 161 | Line(Image, [x1, y2], [x1, y1], VerticalOrientation) 162 | 163 | 164 | ##################################################################################################### 165 | 166 | # Drawing ellipse 167 | def Ellipse(Image, Center, Axes, Angle, startAngle, endAngle): 168 | if Axes[0] == 0 and Axes[1] == 0: 169 | return 170 | 171 | # each segment will make angle theta with the center 172 | theta = int(np.round(np.degrees(((2 * Len) / (Axes[0] + Axes[1]))))) 173 | 174 | PartAngles = [i for i in range(0, 360+theta+1, theta)] 175 | 176 | isWhite = True 177 | for i in range(1, len(PartAngles)): 178 | if isWhite: 179 | cv2.ellipse(Image, Center, Axes, Angle, PartAngles[i-1], PartAngles[i], (255, )*Image.shape[-1], 1) 180 | isWhite = False 181 | else: 182 | cv2.ellipse(Image, Center, Axes, Angle, PartAngles[i-1], PartAngles[i], (0, )*Image.shape[-1], 1) 183 | isWhite = True 184 | 185 | ##################################################################################################### 186 | 187 | # Drawing incomplete (open) contour. Instead of dashed lines, 188 | # colour of each point depends on the image brightness at that point. 189 | def Inc_Contour(Image, Contour): 190 | # Looping over all points 191 | for i in range(1, len(Contour)): 192 | # Extracting the grayscale colour of the point 193 | ColourVal = Image[Contour[i][1]][Contour[i][0]] 194 | 195 | if ColourVal[0] <= 127 and ColourVal[1] <= 127 and ColourVal[2] <= 127: 196 | cv2.line(Image, tuple(Contour[i]), tuple(Contour[i-1]), (255, 255, 255), 1) 197 | 198 | else: 199 | cv2.line(Image, tuple(Contour[i]), tuple(Contour[i-1]), (0, 0, 0), 1) 200 | 201 | 202 | # Drawing complete (closed) contour with dashed lines. 203 | def Com_Contours(Image, Contours): 204 | for Contour in Contours: # For each contour 205 | Sum = 0 206 | isWhite = True 207 | 208 | # is contour point of the type [x, y] or [[x, y]] 209 | if len(Contour[0]) == 1: 210 | isExtraAxis = True 211 | else: 212 | isExtraAxis = False 213 | 214 | # Looping on each point of the contour 215 | for i in range(1, len(Contour)): 216 | if isExtraAxis: 217 | x1, y1 = Contour[i-1][0] 218 | x2, y2 = Contour[i][0] 219 | else: 220 | x1, y1 = Contour[i-1] 221 | x2, y2 = Contour[i] 222 | 223 | # Distance between two consecutive points of the contour 224 | dist = hf.Distance([x1, y1], [x2, y2]) 225 | 226 | # Connecting these points with a line 227 | if isWhite: 228 | cv2.line(Image, (x1, y1), (x2, y2), (255, 255, 255), 1) 229 | else: 230 | cv2.line(Image, (x1, y1), (x2, y2), (0, 0, 0), 1) 231 | 232 | # Checking if part length exceeded. If yes, then switch colour. 233 | Sum += dist 234 | if Sum > Len: 235 | isWhite = not isWhite 236 | Sum = 0 237 | 238 | # Joining the first and last points 239 | if isExtraAxis: 240 | x1, y1 = Contour[0][0] 241 | x2, y2 = Contour[-1][0] 242 | else: 243 | x1, y1 = Contour[0] 244 | x2, y2 = Contour[-1] 245 | 246 | LineAtAngle(Image, [x1, y1], [x2, y2], True) 247 | -------------------------------------------------------------------------------- /selectRegionClass.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | import input_output 5 | import helping_functions as hf 6 | 7 | 8 | 9 | class _SelectRegion: 10 | def __init__(self, Canvas, window_title, AskLayerNames=True, CorrectXYWhileSelecting=True, RegionMovable=True): 11 | hf.Clear() # Clearing the terminal 12 | self.Canvas = Canvas 13 | self.window_title = window_title 14 | self.RegionMovable = RegionMovable 15 | 16 | # Asking layer numbers if prompted 17 | if AskLayerNames: 18 | # Taking layer numbers user wants to copy 19 | self.Canvas.PrintLayerNames() 20 | if len(self.Canvas.layers) <= 1: 21 | self.layer_nos_to_copy = [-1] 22 | print("\nThe tool will copy the only layer present.") 23 | else: 24 | self.layer_nos_to_copy = AskLayerNumsToCopy(-1, len(self.Canvas.layers) - 1) 25 | 26 | # Printing help statements common for all selection tools in Photoshop 27 | print("\nPress 'Y' to confirm selection and copy it in a new layer else press 'N' to abort.") 28 | if self.RegionMovable: 29 | print("You can also used the keys 'W', 'A', 'S', and 'D', to move the") 30 | print("selected region Up, Left, Down, and Right respectively.\n") 31 | self.PrintInstructions() 32 | 33 | # Clearing mouse buffer data (old mouse data) - this is a bug in OpenCV probably 34 | cv2.namedWindow(self.window_title) 35 | cv2.setMouseCallback(self.window_title, hf.EmptyCallBackFunc) 36 | self.Canvas.Show(Title=self.window_title) 37 | cv2.waitKey(1) 38 | 39 | # Setting mouse callback 40 | cv2.setMouseCallback(self.window_title, self.CallBackFunc) 41 | 42 | # Setting variables for use 43 | self.selecting = False # True if region is being selected 44 | self.isSelected = False # True if region is selected 45 | self.Canvas.CombineLayers() 46 | self.CombinedFrame = self.Canvas.CombinedImage.copy() # the combined frame of the canvas 47 | self.FrameToShow = self.CombinedFrame.copy() # The frame which will be shown (with the selected region) 48 | self.CanvasShape = self.Canvas.Shape # Shape of the canvas 49 | self.Key = -1 # waitKey() return value 50 | 51 | # Correct value of mouse pointer while selecting 52 | self.CorrectXYWhileSelecting = CorrectXYWhileSelecting 53 | 54 | # Selected region's mask and BB variables to be used later 55 | self.Selected_BB, self.Selected_Mask = None, None 56 | 57 | 58 | def CallBackFunc(self, event, x, y, flags, params): 59 | # If while selecting the region, mouse goes out of the frame, then clip it position 60 | # to the nearest corner/edge of the frame 61 | if self.selecting and self.CorrectXYWhileSelecting: 62 | x, y = hf.Correct_xy_While_Selecting(x, y, [0, self.CanvasShape[1]-1], [0, self.CanvasShape[0]-1]) 63 | 64 | # Storing mouse pointer values to self variable for access outside the function 65 | self.x, self.y = x, y 66 | 67 | # Starts selecting - Left button is pressed down 68 | if event == cv2.EVENT_LBUTTONDOWN: 69 | self.selecting = True 70 | self.isSelected = False 71 | self.Mouse_EVENT_LBUTTONDOWN() 72 | 73 | # Selecting the region 74 | elif event == cv2.EVENT_MOUSEMOVE: 75 | if self.selecting: 76 | self.Mouse_EVENT_MOUSEMOVE_selecting() 77 | self.SetCanvasFrame() 78 | 79 | # Stop selecting the layer. 80 | elif event == cv2.EVENT_LBUTTONUP: 81 | self.selecting = False 82 | self.isSelected = True 83 | self.Mouse_EVENT_LBUTTONUP() 84 | self.SetCanvasFrame() 85 | 86 | else: 87 | self.Other_MouseEvents(event) 88 | 89 | 90 | def RunTool(self): 91 | self.IsAborted = False 92 | while True: 93 | # Showing canvas 94 | cv2.imshow(self.window_title, self.FrameToShow) 95 | self.Key = cv2.waitKey(1) 96 | 97 | if self.Key == 89 or self.Key == 121: # If 'Y'/'y' - confirm 98 | if self.isSelected: # If the region is selected 99 | break 100 | else: # If the region is not selected yet 101 | print("Select a region first to confirm.") 102 | continue 103 | elif self.Key == 78 or self.Key == 110: # If 'N'/'n' - abort 104 | self.IsAborted = True 105 | break 106 | else: 107 | self.KeyPressedInMainLoop() 108 | 109 | # If the region is selected, check if the user is trying to move it 110 | if self.isSelected and self.RegionMovable: 111 | if self.Key != -1: # If some key is pressed 112 | self.Region_isSelected() 113 | self.SetCanvasFrame() 114 | 115 | 116 | if not self.IsAborted: 117 | self.GetSelectedRegionDetails() 118 | if self.Selected_BB is None or self.Selected_Mask is None: 119 | raise ValueError("Selected region's BB or Mask not set.") 120 | ExtractSelectedRegion(self.Canvas, self.Selected_BB, self.Selected_Mask, self.layer_nos_to_copy) 121 | 122 | else: 123 | print("\nRegion selection aborted.") 124 | 125 | 126 | def SetCanvasFrame(self): 127 | self.FrameToShow = self.CombinedFrame.copy() 128 | self.DrawRegion() 129 | 130 | def DrawRegion(self): 131 | raise NotImplementedError("Method \"DrawRegion\" is not implemented.") 132 | 133 | def Mouse_EVENT_LBUTTONDOWN(self): 134 | raise NotImplementedError("Method \"Mouse_EVENT_LBUTTONDOWN\" is not implemented.") 135 | 136 | def Mouse_EVENT_MOUSEMOVE_selecting(self): 137 | raise NotImplementedError("Method \"Mouse_EVENT_MOUSEMOVE_selecting\" is not implemented.") 138 | 139 | def Mouse_EVENT_LBUTTONUP(self): 140 | raise NotImplementedError("Method \"Mouse_EVENT_LBUTTONUP\" is not implemented.") 141 | 142 | def Region_isSelected(self): 143 | raise NotImplementedError("Method \"Region_isSelected\" is not implemented.") 144 | 145 | def GetSelectedRegionDetails(self): 146 | raise NotImplementedError("Method \"GetSelectedRegionDetails\" is not implemented.") 147 | 148 | def PrintInstructions(self): 149 | pass 150 | 151 | def Other_MouseEvents(self, Event): 152 | pass 153 | 154 | def KeyPressedInMainLoop(self): 155 | pass 156 | 157 | 158 | ########################################################################################################### 159 | 160 | def AskLayerNumsToCopy(a, b): 161 | while True: 162 | print("\nEnter the layer numbers you want to copy with this tool (-1 for all layers).") 163 | layer_nos = input_output.AskForLayerNumbers(a, b) 164 | 165 | if layer_nos is None: 166 | print("You must enter atleast one layer number.") 167 | continue 168 | else: 169 | return layer_nos 170 | 171 | 172 | def CropVisible(Image): 173 | # Extracting alpha channel 174 | Alpha = Image[:, :, [-1]] 175 | 176 | # Thresholding alpha channel (all values > 0 = 255) 177 | AlphaTh = cv2.threshold(Alpha, 1, 255, cv2.THRESH_BINARY)[1] 178 | 179 | # Finding contours 180 | Contours, _ = cv2.findContours(AlphaTh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 181 | 182 | # If no contours found - return None (no visible part) 183 | if len(Contours) == 0: 184 | return None 185 | 186 | # Extracting bounding box of the visible part(s) 187 | BB = cv2.boundingRect(Contours[0]) 188 | if len(Contours) > 1: # Taking union of bounding boxes if more than one 189 | for i in range(1, len(Contours)): 190 | BB = hf.Union(BB, cv2.boundingRect(Contours[i])) 191 | 192 | # Cropping out the visible part 193 | VisiblePartImage = Image[BB[1] : BB[1] + BB[3], BB[0] : BB[0] + BB[2]].copy() 194 | 195 | return VisiblePartImage 196 | 197 | 198 | 199 | def ExtractSelectedRegion(Canvas, Selected_BB, Selected_Mask, layer_nos): 200 | # Bounding box of the region 201 | [x, y, w, h] = Selected_BB 202 | 203 | # Sorting the layer numbers in increasing order 204 | if layer_nos.count(-1) != 0: 205 | layer_nos = [i for i in range(len(Canvas.layers))] 206 | layer_nos = sorted(layer_nos) 207 | 208 | # Selected region combined image 209 | Selected_Image = np.zeros((h, w, 4), dtype=np.uint8) 210 | 211 | for layer_no in layer_nos: 212 | # Intersecting rectangle 213 | # IntRect is the coordinates of intersecting rectange wrt the canvas 214 | IntRect = hf.Intersection(Selected_BB, Canvas.layers[layer_no].Position + list(Canvas.layers[layer_no].Shape)[::-1]) 215 | if IntRect is None: # If no intersecting part 216 | continue 217 | # Converting IntRect to wrt image and wrt selected region 218 | IntRect_Image = [IntRect[0] - Canvas.layers[layer_no].Position[0], 219 | IntRect[1] - Canvas.layers[layer_no].Position[1], 220 | IntRect[2], IntRect[3]] 221 | IntRect_Region = [IntRect[0] - Selected_BB[0], IntRect[1] - Selected_BB[1], 222 | IntRect[2], IntRect[3]] 223 | _x, _y, _w, _h = IntRect_Region 224 | 225 | # Cropping out layer's image 226 | LayerImg = Canvas.layers[layer_no].Image[IntRect_Image[1] : IntRect_Image[1]+IntRect_Image[3], 227 | IntRect_Image[0] : IntRect_Image[0]+IntRect_Image[2]].copy() 228 | 229 | # Adding these layer images to the selected image 230 | alpha = LayerImg[:, :, [-1]].astype(float)/255 231 | alpha = cv2.merge((alpha, alpha, alpha)) 232 | Selected_Image[_y:_y+_h, _x:_x+_w, :-1] = cv2.add(cv2.multiply(alpha, LayerImg[:, :, :-1], dtype=cv2.CV_64F), 233 | cv2.multiply(1.0 - alpha, Selected_Image[_y:_y+_h, _x:_x+_w, :-1], dtype=cv2.CV_64F)) 234 | Selected_Image[_y:_y+_h, _x:_x+_w, -1] = cv2.max(LayerImg[:, :, [-1]], Selected_Image[_y:_y+_h, _x:_x+_w, [-1]]) 235 | 236 | # Masking the part of image invisible that was not in the selected region mask 237 | Selected_Image[:, :, -1] = cv2.bitwise_and(Selected_Image[:, :, [-1]], Selected_Mask) 238 | 239 | # Crop the visible part of the selected image (alpha > 0) 240 | Selected_Image = CropVisible(Selected_Image) 241 | if Selected_Image is None: 242 | print("\nSelected region is empty. No new layer creared.") 243 | return 244 | 245 | # Add the new layer of the selected region 246 | Canvas.AddLayer(Selected_Image, Index=(layer_nos[-1]+1)) 247 | 248 | 249 | 250 | -------------------------------------------------------------------------------- /marquee.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | import drawing 5 | import selectRegionClass 6 | import helping_functions as hf 7 | 8 | 9 | 10 | ####################################################### Rectangular Marquee Tool ############################################################################## 11 | 12 | class _RectangularMarqueeToolClass(selectRegionClass._SelectRegion): 13 | def __init__(self, Canvas, window_title, AskLayerNames=True, CorrectXYWhileSelecting=True, RegionMovable=True): 14 | super().__init__(Canvas, window_title, AskLayerNames=AskLayerNames, 15 | CorrectXYWhileSelecting=CorrectXYWhileSelecting, RegionMovable=RegionMovable) 16 | 17 | # Selected rectangle position of top left and bottom right corner 18 | self.X1_, self.Y1_ = 0, 0 19 | self.X2_, self.Y2_ = 0, 0 20 | 21 | # Defining how to draw the selected region 22 | def DrawRegion(self): 23 | drawing.Rectangle(self.FrameToShow, [self.X1_, self.Y1_], [self.X2_, self.Y2_]) 24 | 25 | # If left button is pressed 26 | def Mouse_EVENT_LBUTTONDOWN(self): 27 | self.X1_, self.Y1_ = self.x, self.y 28 | 29 | # If mouse is moved while selecting the region 30 | def Mouse_EVENT_MOUSEMOVE_selecting(self): 31 | self.X2_, self.Y2_ = self.x, self.y 32 | 33 | # If mouse left button is released 34 | def Mouse_EVENT_LBUTTONUP(self): 35 | self.X2_, self.Y2_ = self.x, self.y 36 | if self.X1_ == self.X2_ and self.Y1_ == self.Y2_: 37 | self.isSelected = False 38 | 39 | # Inside the while loop if the area is selected 40 | def Region_isSelected(self): 41 | if self.Key == 87 or self.Key == 119: # If 'W'/'w' - move up 42 | self.Y1_ -= 1 43 | self.Y2_ -= 1 44 | elif self.Key == 65 or self.Key == 97: # If 'A'/'a' - move left 45 | self.X1_ -= 1 46 | self.X2_ -= 1 47 | elif self.Key == 83 or self.Key == 115: # If 'S'/'s' - move down 48 | self.Y1_ += 1 49 | self.Y2_ += 1 50 | elif self.Key == 68 or self.Key == 100: # If 'D'/'d' - move right 51 | self.X1_ += 1 52 | self.X2_ += 1 53 | 54 | # If the region is selected and confirmed, setting selected region details 55 | def GetSelectedRegionDetails(self): 56 | # Correcting rectangular's points 57 | self.X1_, self.Y1_, self.X2_, self.Y2_ = hf.CorrectRectPoints(self.X1_, self.Y1_, self.X2_, self.Y2_) 58 | self.Selected_BB = [self.X1_, self.Y1_, (self.X2_-self.X1_+1), (self.Y2_-self.Y1_+1)] 59 | self.Selected_Mask = np.ones((self.Selected_BB[3], self.Selected_BB[2], 1), dtype=np.uint8) * 255 60 | 61 | 62 | def RectangularMarqueeTool(Canvas, window_title): 63 | ToolObject = _RectangularMarqueeToolClass(Canvas, window_title) 64 | ToolObject.RunTool() 65 | 66 | 67 | ############################################################################################################################################################### 68 | 69 | 70 | ######################################################## Elliptical Marquee Tool ############################################################################## 71 | 72 | class _EllipticalMarqueeToolClass(selectRegionClass._SelectRegion): 73 | def __init__(self, Canvas, window_title, AskLayerNames=True, CorrectXYWhileSelecting=False, RegionMovable=True): 74 | super().__init__(Canvas, window_title, AskLayerNames=AskLayerNames, 75 | CorrectXYWhileSelecting=CorrectXYWhileSelecting, RegionMovable=RegionMovable) 76 | # Initializing the variables for this tool 77 | # Position of mouse from where ellipse is started selecting 78 | self.ix, self.iy = 0, 0 79 | # Selected ellipse's center coordinates and lengths of major and minor axes 80 | self.X_, self.Y_, self.A_, self.B_ = 0, 0, 0, 0 81 | 82 | # Draw the selected region 83 | def DrawRegion(self): 84 | drawing.Ellipse(self.FrameToShow, (self.X_, self.Y_), (self.A_, self.B_), 0, 0, 360) 85 | 86 | # Mouse left button is pressed down, set initial points of ellipse 87 | def Mouse_EVENT_LBUTTONDOWN(self): 88 | self.ix, self.iy = self.x, self.y 89 | 90 | # When selecting and mouse is moving, get and draw ellipse 91 | def Mouse_EVENT_MOUSEMOVE_selecting(self): 92 | self.X_, self.Y_ = (self.ix + self.x)//2, (self.iy + self.y)//2 93 | self.A_, self.B_ = abs(self.ix - self.x)//2, abs(self.iy - self.y)//2 94 | 95 | # Mouse left button released, set ellipse data and draw ellipse 96 | def Mouse_EVENT_LBUTTONUP(self): 97 | self.X_, self.Y_ = (self.ix + self.x)//2, (self.iy + self.y)//2 98 | self.A_, self.B_ = abs(self.ix - self.x)//2, abs(self.iy - self.y)//2 99 | if self.ix == self.x and self.iy == self.y: 100 | self.isSelected = False 101 | 102 | # If region is selected and being moved 103 | def Region_isSelected(self): 104 | if self.Key == 87 or self.Key == 119: # If 'W'/'w' - move up 105 | self.Y_ -= 1 106 | elif self.Key == 65 or self.Key == 97: # If 'A'/'a' - move left 107 | self.X_ -= 1 108 | elif self.Key == 83 or self.Key == 115: # If 'S'/'s' - move down 109 | self.Y_ += 1 110 | elif self.Key == 68 or self.Key == 100: # If 'D'/'d' - move right 111 | self.X_ += 1 112 | 113 | # Getting bounding box and the mask image of the selected region 114 | def GetSelectedRegionDetails(self): 115 | # Correcting rectangular's points 116 | self.Selected_BB = [self.X_ - self.A_, self.Y_ - self.B_, 2*self.A_, 2*self.B_] 117 | self.Selected_Mask = np.zeros((self.Selected_BB[3], self.Selected_BB[2], 1), dtype=np.uint8) 118 | cv2.ellipse(self.Selected_Mask, (self.A_, self.B_), (self.A_, self.B_), 0, 0, 360, 255, -1) 119 | 120 | 121 | 122 | def EllipticalMarqueeTool(Canvas, window_title): 123 | ToolObject = _EllipticalMarqueeToolClass(Canvas, window_title) 124 | ToolObject.RunTool() 125 | 126 | 127 | ############################################################################################################################################################### 128 | 129 | ######################################################## Single Row Marquee Tool ############################################################################## 130 | 131 | class _SingleRowMarqueeToolClass(selectRegionClass._SelectRegion): 132 | def __init__(self, Canvas, window_title, AskLayerNames=True, CorrectXYWhileSelecting=True, RegionMovable=True): 133 | super().__init__(Canvas, window_title, AskLayerNames=AskLayerNames, 134 | CorrectXYWhileSelecting=CorrectXYWhileSelecting, RegionMovable=RegionMovable) 135 | 136 | self.X_ = 0 # Starting point of the row selected 137 | self.Y_ = 0 # Y-coordinate of the row selected 138 | 139 | # Drawing selected line 140 | def DrawRegion(self): 141 | drawing.HorLine(self.FrameToShow, self.X_, self.X_ + self.CanvasShape[1]-1, self.Y_) 142 | 143 | # Mouse left button is pressed down 144 | def Mouse_EVENT_LBUTTONDOWN(self): 145 | self.X_ = 0 146 | self.Y_ = self.y 147 | 148 | # Mouse is moved while selecting the region 149 | def Mouse_EVENT_MOUSEMOVE_selecting(self): 150 | self.Y_ = self.y 151 | 152 | # Mouse left button is released 153 | def Mouse_EVENT_LBUTTONUP(self): 154 | self.Y_ = self.y 155 | 156 | # When region is selected - move it 157 | def Region_isSelected(self): 158 | if self.Key == 87 or self.Key == 119: # If 'W'/'w' - move up 159 | self.Y_ -= 1 160 | elif self.Key == 65 or self.Key == 97: # If 'A'/'a' - move left 161 | self.X_ -= 1 162 | elif self.Key == 83 or self.Key == 115: # If 'S'/'s' - move down 163 | self.Y_ += 1 164 | elif self.Key == 68 or self.Key == 100: # If 'D'/'d' - move right 165 | self.X_ += 1 166 | 167 | # When region is selected, setting bounding box and mask of the selected region 168 | def GetSelectedRegionDetails(self): 169 | # Correcting rectangular's points 170 | self.Selected_BB = [self.X_, self.Y_, self.CanvasShape[1], 1] 171 | self.Selected_Mask = np.ones((self.Selected_BB[3], self.Selected_BB[2], 1), dtype=np.uint8) * 255 172 | 173 | 174 | def SingleRowMarqueeTool(Canvas, window_title): 175 | ToolObject = _SingleRowMarqueeToolClass(Canvas, window_title) 176 | ToolObject.RunTool() 177 | 178 | 179 | ############################################################################################################################################################### 180 | 181 | ######################################################## Single Column Marquee Tool ########################################################################### 182 | 183 | class _SingleColMarqueeToolClass(selectRegionClass._SelectRegion): 184 | def __init__(self, Canvas, window_title, AskLayerNames=True, CorrectXYWhileSelecting=True, RegionMovable=True): 185 | super().__init__(Canvas, window_title, AskLayerNames=AskLayerNames, 186 | CorrectXYWhileSelecting=CorrectXYWhileSelecting, RegionMovable=RegionMovable) 187 | 188 | self.X_ = 0 # Starting point of the row selected 189 | self.Y_ = 0 # Y-coordinate of the row selected 190 | 191 | # Drawing selected line 192 | def DrawRegion(self): 193 | drawing.VerLine(self.FrameToShow, self.X_, self.Y_, self.Y_ + self.CanvasShape[0]-1) 194 | 195 | # Mouse left button is pressed down 196 | def Mouse_EVENT_LBUTTONDOWN(self): 197 | self.X_ = self.x 198 | self.Y_ = 0 199 | 200 | # Mouse is moved while selecting the region 201 | def Mouse_EVENT_MOUSEMOVE_selecting(self): 202 | self.X_ = self.x 203 | 204 | # Mouse left button is released 205 | def Mouse_EVENT_LBUTTONUP(self): 206 | self.X_ = self.x 207 | 208 | # When region is selected - move it 209 | def Region_isSelected(self): 210 | if self.Key == 87 or self.Key == 119: # If 'W'/'w' - move up 211 | self.Y_ -= 1 212 | elif self.Key == 65 or self.Key == 97: # If 'A'/'a' - move left 213 | self.X_ -= 1 214 | elif self.Key == 83 or self.Key == 115: # If 'S'/'s' - move down 215 | self.Y_ += 1 216 | elif self.Key == 68 or self.Key == 100: # If 'D'/'d' - move right 217 | self.X_ += 1 218 | 219 | # When region is selected, setting bounding box and mask of the selected region 220 | def GetSelectedRegionDetails(self): 221 | # Correcting rectangular's points 222 | self.Selected_BB = [self.X_, self.Y_, 1, self.CanvasShape[0]] 223 | self.Selected_Mask = np.ones((self.Selected_BB[3], self.Selected_BB[2], 1), dtype=np.uint8) * 255 224 | 225 | 226 | def SingleColMarqueeTool(Canvas, window_title): 227 | ToolObject = _SingleColMarqueeToolClass(Canvas, window_title) 228 | ToolObject.RunTool() 229 | 230 | ############################################################################################################################################################### 231 | -------------------------------------------------------------------------------- /layers.py: -------------------------------------------------------------------------------- 1 | import os 2 | import cv2 3 | import numpy as np 4 | 5 | import image 6 | import macros as m 7 | import helping_functions as hf 8 | 9 | 10 | 11 | # This class contains the details and objects about a single layer only 12 | class _layer: 13 | def __init__(self, Image, IsVisible=True, Position=[0, 0], Name=None): 14 | self.Image = Image 15 | self.CheckImage() 16 | 17 | self.Shape = Image.shape[:2] 18 | self.IsVisible = IsVisible 19 | self.Position = Position 20 | self.Name = Name 21 | 22 | 23 | # Checking the image dimentions (should be 4 channeled) 24 | def CheckImage(self): 25 | c = self.Image.shape[2] 26 | if c != 4: 27 | raise TypeError("Image should be 4 channeled.") 28 | 29 | 30 | def Copy(self): 31 | Layer_copy = _layer(self.Image.copy(), IsVisible=self.IsVisible, 32 | Position=self.Position.copy(), 33 | Name=''.join(self.Name)) 34 | 35 | return Layer_copy 36 | 37 | 38 | # This class creates the main object of the project will all layers as list 39 | # This class contains the methods for manipulating the different layers together. 40 | class _canvas: 41 | def __init__(self, **kwargs): 42 | self.BackgroundImg = None # Background image will be stored here 43 | self.layers = [] # All the other layers will be stored in this list 44 | 45 | if "layer" in kwargs: # If layer is passed 46 | FirstLayer = kwargs["layer"] # Getting the first layer 47 | 48 | # Storing the background image 49 | self.BackgroundImg = image.CreateBackgroundImage(FirstLayer.Shape) 50 | # Adding the first layer 51 | self.layers.append(FirstLayer) 52 | 53 | # Storing only the background image depending on the shape if passed 54 | elif "shape" in kwargs: 55 | self.BackgroundImg = image.CreateBackgroundImage(kwargs["shape"]) 56 | else: 57 | self.BackgroundImg = image.CreateBackgroundImage([m.DEFAULT_CANVAS_HEIGHT, m.DEFAULT_CANVAS_WIDTH]) 58 | 59 | self.Shape = self.BackgroundImg.shape[:2] 60 | 61 | 62 | def AddLayer(self, Image, Index=None): 63 | NewLayer = _layer(Image, Name="Layer " + str(len(self.layers))) 64 | 65 | # Adding new layer at the mentioned index 66 | if Index is None: 67 | self.layers.append(NewLayer) 68 | else: 69 | self.layers.insert(Index, NewLayer) 70 | 71 | 72 | 73 | def CombineLayers(self): 74 | # Taking the background first 75 | self.CombinedImage = self.BackgroundImg.copy() 76 | 77 | # Combine layers one by one 78 | for i in range(len(self.layers)): 79 | # Combining if it is marked visible. 80 | if self.layers[i].IsVisible: 81 | 82 | # Getting image roi and canvas roi 83 | Image_ROI, Canvas_ROI = hf.Get_Img_Canvas_ROI(list(self.layers[i].Position) + list(self.layers[i].Shape)[::-1], self.Shape) 84 | if Image_ROI is None: # If image completely lies outside the canvas 85 | continue 86 | i_x, i_y, i_w, i_h = Image_ROI 87 | c_x, c_y, c_w, c_h = Canvas_ROI 88 | Image_ROI_img = self.layers[i].Image[i_y : i_y + i_h, i_x : i_x + i_w].copy() 89 | Canvas_ROI_img = self.CombinedImage[c_y : c_y + c_h, c_x : c_x + c_w].copy() 90 | 91 | # Extracting alpha channel, normalising it to range 0-1. 92 | alpha = Image_ROI_img[:, :, [-1]].astype(float)/255 93 | # Creating 3 channeled image from alpha channel 94 | alpha = cv2.merge((alpha, alpha, alpha)) 95 | 96 | # Combining layer to the previously combined layers. 97 | self.CombinedImage[c_y : c_y + c_h, c_x : c_x + c_w] = cv2.add(cv2.multiply(alpha, Image_ROI_img[:, :, :-1], dtype=cv2.CV_64F), 98 | cv2.multiply(1.0 - alpha, Canvas_ROI_img, dtype=cv2.CV_64F)) 99 | 100 | # Converting it to unsigned int. 101 | self.CombinedImage = np.uint8(self.CombinedImage) 102 | 103 | 104 | def Show(self, Title=m.DEFAULT_CANVAS_TITLE): 105 | # Checking title type. It should be string. 106 | if type(Title) != str: 107 | raise TypeError("Title must be a string.") 108 | 109 | # Combining all layers 110 | self.CombineLayers() 111 | 112 | # Showing the combined layers. 113 | cv2.imshow(Title, self.CombinedImage) 114 | 115 | 116 | def PrintLayerNames(self): 117 | # Print layer names except backgroud layer name. 118 | print("\nLayers present are:") 119 | for i in range(len(self.layers)): 120 | print("{} : {}".format(i, self.layers[i].Name)) 121 | 122 | 123 | def Copy(self, copyTo=None): 124 | if copyTo is None: 125 | Canvas_copy = _canvas(shape=self.Shape) 126 | else: 127 | Canvas_copy = copyTo 128 | 129 | Canvas_copy.layers = [self.layers[i].Copy() for i in range(len(self.layers))] 130 | 131 | 132 | # Copying all other data of Canvas 133 | Canvas_copy.BackgroundImg = self.BackgroundImg.copy() # Images can be copied like this 134 | Canvas_copy.Shape = self.Shape + tuple() 135 | Canvas_copy.CombinedImage = self.CombinedImage.copy() 136 | 137 | return Canvas_copy 138 | 139 | def SetLayersVisibility(self, layer_nos): 140 | # If -1 entered - Show all layers 141 | if layer_nos.count(-1) != 0: 142 | for i in range(len(self.layers)): 143 | self.layers[i].IsVisible = True 144 | 145 | # If -2 entered - Show no layer 146 | elif layer_nos.count(-2) != 0: 147 | for i in range(len(self.layers)): 148 | self.layers[i].IsVisible = False 149 | 150 | # If valid layer numbers passed, show them 151 | else: 152 | for layer_no in range(len(self.layers)): 153 | if layer_nos.count(layer_no): 154 | self.layers[layer_no].IsVisible = True 155 | else: 156 | self.layers[layer_no].IsVisible = False 157 | 158 | 159 | def DeleteLayers(self, layer_nos): 160 | # Sorting layer_nos in decreasing order 161 | layer_nos = sorted(layer_nos, reverse=True) 162 | 163 | # Deleting the layers 164 | for layer_no in layer_nos: 165 | del self.layers[layer_no] 166 | 167 | 168 | def ExchangeLayers(self, l1, l2): 169 | self.layers[l1], self.layers[l2] = self.layers[l2], self.layers[l1] 170 | 171 | 172 | def MergeLayers(self, layer_nos): 173 | # Storting layer numbers in increasing order 174 | layer_nos = sorted(layer_nos) 175 | # Merged layer will be stored in place of the top-most 176 | # layer's pos among the layers which are being merged. 177 | merged_layer_no = layer_nos[-1] 178 | 179 | # Getting Merged layer name. (Merged: l1_name + l2_name + ....) 180 | merged_layer_name = "Merged: " 181 | for i in layer_nos: 182 | merged_layer_name = merged_layer_name + self.layers[i].Name + " + " 183 | merged_layer_name = merged_layer_name[:-3] # Removing last " + " 184 | 185 | 186 | # Joining/Merging all images and getting merged image position. 187 | merged_img, merged_img_pos, merged_img_shape = JoinImages([self.layers[i].Image.copy() for i in layer_nos], 188 | [self.layers[i].Position for i in layer_nos], 189 | [self.layers[i].Shape for i in layer_nos]) 190 | 191 | # Storing merged layers data. 192 | self.layers[merged_layer_no].Image = merged_img 193 | self.layers[merged_layer_no].IsVisible = True 194 | self.layers[merged_layer_no].Position = merged_img_pos 195 | self.layers[merged_layer_no].Shape = merged_img_shape 196 | self.layers[merged_layer_no].Name = merged_layer_name 197 | 198 | # Deleting all the remaining layers. 199 | self.DeleteLayers(layer_nos[:-1]) 200 | 201 | 202 | def RenameLayer(self, layer_no, rename_to): 203 | # Renaming the layer. 204 | self.layers[layer_no].Name = rename_to 205 | 206 | 207 | def DuplicateLayer(self, layer_no): 208 | # Copying the layer. and changing its name to " copy" 209 | LayerCopy = self.layers[layer_no].Copy() 210 | LayerCopy.Name += " copy" 211 | 212 | # Storing this layer on the top of "layer_no" 213 | self.layers.insert(layer_no+1, LayerCopy) 214 | 215 | 216 | 217 | 218 | # Initializes the project layers 219 | def Initialize(args): 220 | if args["ImagePath"] is not None: # If image path is passed 221 | # Reading the image 222 | Img = image.ReadImage(args["ImagePath"]) 223 | # If image path is not correct - exit 224 | if Img is None: 225 | print("\nProvide a correct image path.\n") 226 | exit() 227 | 228 | # Creating the first layer and Canvas object 229 | FirstLayer = _layer(Img, Name="Layer 0", Position=[0, 0]) 230 | Canvas = _canvas(layer=FirstLayer) 231 | 232 | else: 233 | # If shape is provided, use it, else, take default shape 234 | if args["Shape"] is not None: 235 | Shape = args["Shape"] 236 | else: 237 | Shape = [m.DEFAULT_CANVAS_HEIGHT, m.DEFAULT_CANVAS_WIDTH] 238 | 239 | # Creating Canvas object 240 | Canvas = _canvas(shape=Shape) 241 | 242 | 243 | return Canvas 244 | 245 | 246 | def JoinImages(Images, ImagePositions, ImageShapes): 247 | x1, y1, = np.transpose(np.asarray(ImagePositions)) 248 | h, w = np.transpose(np.asarray(ImageShapes)) 249 | 250 | # Join images and create a single big image. 251 | 252 | # Convert image position format - [x, y, w, h] -> [x1, y1, x2, y2] 253 | x2, y2 = hf.to_xyxy(x1, y1, w, h) 254 | 255 | # Storing the initial image and its position 256 | joined_img = Images[0] 257 | joined_img_pos1 = [x1[0], y1[0]] 258 | joined_img_pos2 = [x2[0], y2[0]] 259 | 260 | for i in range(1, len(Images)): 261 | # [x1_, y1_, x2_, y2_] - Position of combined big image in the canvas 262 | x1_ = min(joined_img_pos1[0], x1[i]) 263 | y1_ = min(joined_img_pos1[1], y1[i]) 264 | x2_ = max(joined_img_pos2[0], x2[i]) 265 | y2_ = max(joined_img_pos2[1], y2[i]) 266 | 267 | 268 | # Relative positions of both the images wrt the combined image - rel_i1_posi, rel_i2_posi 269 | ri1x1, ri1y1 = joined_img_pos1[0] - x1_, joined_img_pos1[1] - y1_ 270 | ri1x2, ri1y2 = joined_img_pos2[0] - x1_, joined_img_pos2[1] - y1_ 271 | ri2x1, ri2y1 = x1[i] - x1_, y1[i] - y1_ 272 | ri2x2, ri2y2 = x2[i] - x1_, y2[i] - y1_ 273 | 274 | # Combining both images to the joined image. 275 | new_img = np.zeros((y2_ - y1_ + 1, x2_ - x1_ + 1, 4), dtype=np.uint8) 276 | # First image (lower image) is added directly 277 | new_img[ri1y1 : ri1y2 + 1, ri1x1 : ri1x2 + 1] = joined_img.copy() 278 | # Second image (upper image) is added wrt the alpha channel 279 | alpha = Images[i][:, :, [-1]].astype(float)/255 280 | alpha = cv2.merge((alpha, alpha, alpha)) 281 | new_img[ri2y1 : ri2y2 + 1, ri2x1 : ri2x2 + 1, :-1] = \ 282 | cv2.add(cv2.multiply(alpha, Images[i][:, :, :-1], dtype=cv2.CV_64F), 283 | cv2.multiply(1.0 - alpha, new_img[ri2y1 : ri2y2 + 1, 284 | ri2x1 : ri2x2 + 1, :-1], 285 | dtype=cv2.CV_64F)) 286 | new_img[ri2y1 : ri2y2 + 1, ri2x1 : ri2x2 + 1, -1] = cv2.max(Images[i][:, :, [-1]], new_img[ri2y1 : ri2y2 + 1, ri2x1 : ri2x2 + 1, [-1]]) 287 | 288 | # For next iteration, first image = current combined image. 289 | joined_img_pos1 = [x1_, y1_] 290 | joined_img_pos2 = [x2_, y2_] 291 | joined_img = new_img.copy() 292 | 293 | # Convert image position back to previous format 294 | ji_x1, ji_y1 = joined_img_pos1[0], joined_img_pos1[1] 295 | ji_w, ji_h = hf.to_xywh(ji_x1, ji_y1, joined_img_pos2[0], joined_img_pos2[1]) 296 | 297 | return joined_img, [ji_x1, ji_y1], [ji_h, ji_w] 298 | 299 | -------------------------------------------------------------------------------- /selection.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | import drawing 5 | import selectRegionClass 6 | import helping_functions as hf 7 | 8 | 9 | ############################################################## Object Selection Tool ########################################################################### 10 | 11 | class _ObjectSelectionToolClass(selectRegionClass._SelectRegion): 12 | def __init__(self, Canvas, window_title, AskLayerNames=True, CorrectXYWhileSelecting=True, RegionMovable=True): 13 | super().__init__(Canvas, window_title, AskLayerNames=AskLayerNames, 14 | CorrectXYWhileSelecting=CorrectXYWhileSelecting, RegionMovable=RegionMovable) 15 | 16 | self.X1, self.Y1 = -1, -1 17 | self.X2, self.Y2 = -1, -1 18 | 19 | self.SelectedContours = [] 20 | 21 | # How to draw the selected region 22 | def DrawRegion(self): 23 | if self.selecting: 24 | drawing.Rectangle(self.FrameToShow, self.SelectedContours[0][0], self.SelectedContours[0][2]) 25 | else: 26 | drawing.Com_Contours(self.FrameToShow, self.SelectedContours) 27 | 28 | # When mouse left button is pressed 29 | def Mouse_EVENT_LBUTTONDOWN(self): 30 | self.X1, self.Y1 = self.x, self.y 31 | self.X2, self.Y2 = self.x, self.y 32 | self.SelectedContours = [] 33 | 34 | # When selecting and mouse is moving 35 | def Mouse_EVENT_MOUSEMOVE_selecting(self): 36 | self.X2, self.Y2 = self.x, self.y 37 | # Converting this selecting rectangle to selected contour for now for visualization 38 | self.SelectedContours = [ np.asarray([[self.X1, self.Y1], 39 | [self.X2, self.Y1], 40 | [self.X2, self.Y2], 41 | [self.X1, self.Y2]]) ] 42 | 43 | # Grabcut algorithm 44 | def ApplyGrabcut(self, ItCount=5, Mode=cv2.GC_INIT_WITH_RECT): 45 | # Creating blank mask image 46 | Mask = np.zeros(self.CombinedFrame.shape[:2], dtype=np.uint8) 47 | 48 | # bgdModel & fgdModel variables to be passed 49 | bgdModel = np.zeros((1, 65), dtype=np.float64) 50 | fgdModel = np.zeros((1, 65), dtype=np.float64) 51 | 52 | # Selection rectangle 53 | Rect = [min(self.X1, self.X2), min(self.Y1, self.Y2), abs(self.X1 - self.X2) + 1, abs(self.Y1 - self.Y2) + 1] 54 | 55 | # Running Grabcut algorithm 56 | cv2.grabCut(self.CombinedFrame.copy(), Mask, Rect, bgdModel, fgdModel, ItCount, Mode) 57 | 58 | # Final mask image of foreground and background 59 | FgBgMask = np.where((Mask==2) | (Mask==0), 0, 1).astype(np.uint8) 60 | 61 | # Detecting contours - there can be more than one regions detected 62 | self.SelectedContours = cv2.findContours(FgBgMask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)[-2] 63 | 64 | 65 | # When mouse left button is released 66 | def Mouse_EVENT_LBUTTONUP(self): 67 | self.X2, self.Y2 = self.x, self.y 68 | if self.X1 == self.X2 and self.Y1 == self.Y2: 69 | self.isSelected = False 70 | return 71 | self.ApplyGrabcut() 72 | 73 | # When region is selected and being moved 74 | def Region_isSelected(self): 75 | if self.Key == 87 or self.Key == 119: # If 'W'/'w' - move up 76 | for i in range(len(self.SelectedContours)): 77 | self.SelectedContours[i] = hf.ShiftContour(self.SelectedContours[i], ToOrigin=False, ShiftBy=[0, -1]) 78 | elif self.Key == 65 or self.Key == 97: # If 'A'/'a' - move left 79 | for i in range(len(self.SelectedContours)): 80 | self.SelectedContours[i] = hf.ShiftContour(self.SelectedContours[i], ToOrigin=False, ShiftBy=[-1, 0]) 81 | elif self.Key == 83 or self.Key == 115: # If 'S'/'s' - move down 82 | for i in range(len(self.SelectedContours)): 83 | self.SelectedContours[i] = hf.ShiftContour(self.SelectedContours[i], ToOrigin=False, ShiftBy=[0, 1]) 84 | elif self.Key == 68 or self.Key == 100: # If 'D'/'d' - move right 85 | for i in range(len(self.SelectedContours)): 86 | self.SelectedContours[i] = hf.ShiftContour(self.SelectedContours[i], ToOrigin=False, ShiftBy=[1, 0]) 87 | 88 | # When region is confirmed 89 | def GetSelectedRegionDetails(self): 90 | # As there can be no contours also 91 | if len(self.SelectedContours) == 0: 92 | self.Selected_BB = [0, 0, 10, 10] 93 | self.Selected_Mask = np.zeros((10, 10, 1), dtype=np.uint8) 94 | return 95 | 96 | # Getting bounding box of the contour - [x1, y1, x2, y2] 97 | def GetBoundingBox(Contour): 98 | BB = cv2.boundingRect(Contour) 99 | return [BB[0], BB[1], BB[0]+BB[2]-1, BB[1]+BB[3]-1] 100 | 101 | # As there can be more than one contours, we have to find a common bounding box 102 | self.Selected_BB = GetBoundingBox(self.SelectedContours[0]) 103 | for i in range(1, len(self.SelectedContours)): 104 | BB = GetBoundingBox(self.SelectedContours[i]) 105 | self.Selected_BB[0] = min(self.Selected_BB[0], BB[0]) 106 | self.Selected_BB[1] = min(self.Selected_BB[1], BB[1]) 107 | self.Selected_BB[2] = max(self.Selected_BB[2], BB[2]) 108 | self.Selected_BB[3] = max(self.Selected_BB[3], BB[3]) 109 | self.Selected_BB[2] = self.Selected_BB[2] - self.Selected_BB[0] + 1 110 | self.Selected_BB[3] = self.Selected_BB[3] - self.Selected_BB[1] + 1 111 | 112 | # Getting the mask image 113 | MaskImage = np.zeros((self.CanvasShape[0], self.CanvasShape[1], 1), dtype=np.uint8) 114 | cv2.drawContours(MaskImage, np.array(self.SelectedContours), -1, 255, -1) 115 | x, y, w, h = self.Selected_BB 116 | self.Selected_Mask = MaskImage[y : y + h, x : x + w].copy() 117 | 118 | 119 | 120 | # Main object selection tool function 121 | def ObjectSelectionTool(Canvas, window_title): 122 | ToolObject = _ObjectSelectionToolClass(Canvas, window_title) 123 | ToolObject.RunTool() 124 | 125 | 126 | ################################################################################################################################################################ 127 | 128 | 129 | ############################################################### Quick Selection Tool ########################################################################### 130 | 131 | class _QuickSelectionToolClass(selectRegionClass._SelectRegion): 132 | def __init__(self, Canvas, window_title, AskLayerNames=True, CorrectXYWhileSelecting=True, RegionMovable=True): 133 | super().__init__(Canvas, window_title, AskLayerNames=AskLayerNames, 134 | CorrectXYWhileSelecting=CorrectXYWhileSelecting, RegionMovable=RegionMovable) 135 | 136 | # All pixels = PR_BG for unknown area 137 | self.RegionMask = np.ones((self.CanvasShape[0], self.CanvasShape[1], 1), dtype=np.uint8) * cv2.GC_PR_BGD 138 | 139 | # Drawing selected regions on the canvas 140 | def DrawRegion(self): 141 | Mask = np.zeros(self.RegionMask.shape, dtype=np.uint8) 142 | Mask[(self.RegionMask==cv2.GC_FGD) | (self.RegionMask==cv2.GC_PR_FGD)] = 255 143 | Contours = cv2.findContours(Mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)[-2] 144 | if len(Contours) != 0: 145 | drawing.Com_Contours(self.FrameToShow, Contours) 146 | 147 | # printing extra instructions 148 | def PrintInstructions(self): 149 | print("Press-Hold and drag mouse left button to Add Selection areas.") 150 | print("The new selection arrea will be added when you release the mouse left button.") 151 | print("Double click mouse left button to Start a New Selection.") 152 | print() 153 | 154 | 155 | def SetRegionMask_Selecting(self): 156 | SelectedPointRadius = 2 157 | cv2.circle(self.RegionMask, (self.x, self.y), SelectedPointRadius, cv2.GC_FGD, -1) 158 | 159 | # Redefining callback method 160 | def CallBackFunc(self, event, x, y, flags, params): 161 | # If while selecting the region, mouse goes out of the frame, then clip it position 162 | # to the nearest corner/edge of the frame 163 | if self.selecting and self.CorrectXYWhileSelecting: 164 | x, y = hf.Correct_xy_While_Selecting(x, y, [0, self.CanvasShape[1]-1], [0, self.CanvasShape[0]-1]) 165 | 166 | # Storing mouse pointer values to self variable for access outside the function 167 | self.x, self.y = x, y 168 | 169 | # Starts selecting - Left button is pressed down 170 | if event == cv2.EVENT_LBUTTONDOWN or event == cv2.EVENT_RBUTTONDOWN: 171 | self.selecting = True 172 | self.isSelected = False 173 | self.SetRegionMask_Selecting() 174 | self.SetCanvasFrame() 175 | 176 | # Selecting the region 177 | elif event == cv2.EVENT_MOUSEMOVE: 178 | if self.selecting: 179 | self.SetRegionMask_Selecting() 180 | self.SetCanvasFrame() 181 | 182 | # Stop selecting the layer. 183 | elif event == cv2.EVENT_LBUTTONUP or event == cv2.EVENT_RBUTTONUP: 184 | self.selecting = False 185 | self.isSelected = True 186 | self.ApplyGrabcut(ItCount=1) 187 | self.SetCanvasFrame() 188 | 189 | # Reset region masks 190 | elif event == cv2.EVENT_LBUTTONDBLCLK: 191 | self.selecting = False 192 | self.isSelected = False 193 | self.RegionMask = np.ones((self.CanvasShape[0], self.CanvasShape[1], 1), dtype=np.uint8) * cv2.GC_PR_BGD 194 | self.SetCanvasFrame() 195 | 196 | 197 | # Applying grabcut 198 | def ApplyGrabcut(self, ItCount=5, Mode=cv2.GC_INIT_WITH_MASK): 199 | # bgdModel & fgdModel variables to be passed 200 | bgdModel = np.zeros((1, 65), dtype=np.float64) 201 | fgdModel = np.zeros((1, 65), dtype=np.float64) 202 | 203 | # Running Grabcut algorithm 204 | try: # Grabcut will throw an error if there is no foreground point in the input mask 205 | GC_Output, bgdModel, fgdModel = cv2.grabCut(self.CombinedFrame, self.RegionMask.copy(), None, bgdModel, fgdModel, ItCount, Mode) 206 | 207 | # Getting the foreground part connected to mouse pointer position only and adding it 208 | # Foreground found is black and background is white for applying floodfill 209 | FGD_Mask = np.ones(GC_Output.shape, dtype=np.uint8) * 255 210 | FGD_Mask[(GC_Output==cv2.GC_FGD) | (GC_Output==cv2.GC_PR_FGD)] = 0 211 | mask = np.zeros((FGD_Mask.shape[0] + 2, FGD_Mask.shape[1] + 2), dtype=np.uint8) 212 | cv2.floodFill(FGD_Mask, mask, (self.x, self.y), 127) 213 | self.RegionMask[FGD_Mask==127] = cv2.GC_FGD 214 | except: # If no foreground point, no need to run floodfill, all points are in background 215 | self.RegionMask[:, :] = cv2.GC_PR_BGD 216 | 217 | # Getting selected region BB and mask 218 | def GetSelectedRegionDetails(self): 219 | self.Selected_Mask = np.zeros(self.RegionMask.shape, dtype=np.uint8) 220 | self.Selected_Mask[(self.RegionMask==cv2.GC_FGD) | (self.RegionMask==cv2.GC_PR_FGD)] = 255 221 | self.Selected_BB = [0, 0, self.CanvasShape[1], self.CanvasShape[0]] 222 | 223 | 224 | 225 | def QuickSelectionTool(Canvas, window_title): 226 | ToolObject = _QuickSelectionToolClass(Canvas, window_title, RegionMovable=False) 227 | ToolObject.RunTool() 228 | 229 | 230 | ################################################################################################################################################################ 231 | 232 | 233 | ############################################################### Magic Wand Tool ################################################################################ 234 | 235 | class _MagicWandToolClass(selectRegionClass._SelectRegion): 236 | def __init__(self, Canvas, window_title, AskLayerNames=True, CorrectXYWhileSelecting=True, RegionMovable=True): 237 | super().__init__(Canvas, window_title, AskLayerNames=AskLayerNames, CorrectXYWhileSelecting=CorrectXYWhileSelecting, RegionMovable=RegionMovable) 238 | 239 | # Tolerance value to be used 240 | self.Tolerance = 32 241 | # Seed point coordinates 242 | self.seed = None 243 | # Mask image of the selected region 244 | self.Mask = np.zeros((self.CanvasShape[0], self.CanvasShape[1], 1), dtype=np.uint8) 245 | # Image to be worked on 246 | self.WorkingImage = cv2.edgePreservingFilter(self.CombinedFrame.copy(), flags=1, sigma_s=11, sigma_r=0.2) 247 | self.WorkingImage = cv2.cvtColor(self.WorkingImage, cv2.COLOR_BGR2GRAY) 248 | 249 | # Printing instructions for setting tolerance value 250 | def PrintInstructions(self): 251 | print("Press 'T' to change Tolerance value (default is 32).") 252 | 253 | def DrawRegion(self): 254 | if not self.selecting: # Don't draw if selecting 255 | Contours= cv2.findContours(self.Mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)[-2] 256 | drawing.Com_Contours(self.FrameToShow, Contours) 257 | 258 | def KeyPressedInMainLoop(self): 259 | if self.Key == 84 or self.Key == 116: # If 'T'/'t' pressed 260 | print("\nCurrent value of Tolerance: {}".format(self.Tolerance)) 261 | while True: 262 | try: 263 | self.Tolerance = abs(int(input("Enter new value (between [0-255]): "))) 264 | break 265 | except: 266 | print("Invalid value entered.") 267 | print("New value of Tolerance: {}".format(self.Tolerance)) 268 | 269 | def Mouse_EVENT_LBUTTONDOWN(self): 270 | # Setting seed point 271 | self.seed = [self.x, self.y] 272 | # Resetting mask image 273 | self.Mask = np.zeros((self.CanvasShape[0], self.CanvasShape[1], 1), dtype=np.uint8) 274 | 275 | def Mouse_EVENT_MOUSEMOVE_selecting(self): 276 | pass 277 | 278 | def Mouse_EVENT_LBUTTONUP(self): 279 | self.Floodfill() 280 | 281 | def Floodfill(self): 282 | mask = np.zeros((self.CanvasShape[0]+2, self.CanvasShape[1]+2), dtype=np.uint8) 283 | _, Image, _, Rect = cv2.floodFill(self.WorkingImage.copy(), mask, tuple(self.seed), 255, 284 | self.Tolerance//2, self.Tolerance//2, cv2.FLOODFILL_FIXED_RANGE) 285 | self.Mask[Rect[1]:Rect[1]+Rect[3], Rect[0]:Rect[0]+Rect[2]][Image[Rect[1]:Rect[1]+Rect[3], Rect[0]:Rect[0]+Rect[2]] == 255] = 255 286 | 287 | def GetSelectedRegionDetails(self): 288 | self.Selected_BB = [0, 0, self.CanvasShape[1], self.CanvasShape[0]] 289 | self.Selected_Mask = self.Mask 290 | 291 | 292 | def MagicWandTool(Canvas, window_title): 293 | ToolObject = _MagicWandToolClass(Canvas, window_title, RegionMovable=False) 294 | ToolObject.RunTool() 295 | 296 | ################################################################################################################################################################ 297 | -------------------------------------------------------------------------------- /input_output.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | import lasso 5 | import image 6 | import marquee 7 | import selection 8 | import helping_functions as hf 9 | 10 | 11 | def AddNewLayer(Canvas): 12 | print("\nEnter '@' to abort adding of new image.") 13 | 14 | while True: 15 | NewImagePath = input("\nEnter image path: ") 16 | 17 | if '@' in NewImagePath: # Abort if '@' entered 18 | print("Aborting adding of image.\n") 19 | break 20 | 21 | # Reading new image 22 | NewImage = image.ReadImage(NewImagePath) 23 | if NewImage is None: # If image is not found/read 24 | print("Enter a valid image path...") 25 | continue 26 | 27 | # Calling function for adding new layer 28 | Canvas.AddLayer(NewImage) 29 | print("\nLayer added successfully.") 30 | 31 | break 32 | 33 | hf.Sleep() 34 | 35 | 36 | def AskForLayerNumbers(a, b): 37 | # range [a, b] denotes the acceptable values of layer numbers 38 | while True: 39 | # Asking user layer numbers 40 | nos = input("Enter layer numbers: ") 41 | 42 | # Getting list of numbers passed. Error is thrown if invalid character passed. 43 | try: 44 | nos = [int(num) for num in nos.replace(" ", "").split(',')] 45 | break 46 | except: 47 | print("\nInvalid layer number passed. Pass layer numbers again.") 48 | continue 49 | 50 | # Checking if numbers passed are if valid range. 51 | for i in nos: 52 | if i < a or i > b: 53 | print("\nInvalid layer number passed. Pass layer numbers again.") 54 | nos = AskForLayerNumbers(a, b) 55 | break 56 | 57 | # If no numbers passed. 58 | if nos is None: 59 | print("\nNo numbers passed") 60 | return None 61 | elif len(nos) == 0: 62 | print("\nNo numbers passed") 63 | return None 64 | 65 | return nos 66 | 67 | 68 | def ChooseLayersToShow(Canvas, window_title): 69 | # Checking boundary condition 70 | if len(Canvas.layers) == 0: # If no layer is present 71 | print("\nYou should have atleast 1 layer to show/hide layers.\n") 72 | return 73 | 74 | print("\nEnter the layer numbers (comma(',') separated) you wish to see.") 75 | print("-1 for all layers and -2 for no layer.\n") 76 | Canvas.PrintLayerNames() 77 | 78 | # Creating a copy of Canvas to work on 79 | Canvas_copy = Canvas.Copy() 80 | 81 | IsAborted = False 82 | while True: 83 | Canvas_copy.Show(Title=window_title) 84 | key = cv2.waitKey(1) 85 | 86 | command = input("\nEnter 'Y/N' to confirm/abort arrangement else enter any other key to select different set of layers: ") 87 | 88 | if 'Y' in command or 'y' in command: # 'Y' or 'y' is pressed. - confirm 89 | break 90 | elif 'N' in command or 'n' in command: # 'N' or 'n' is pressed. - abort 91 | IsAborted = True 92 | break 93 | 94 | # Asking for layer nos and checking if valid umbers passed 95 | layer_nos = AskForLayerNumbers(-2, len(Canvas_copy.layers) - 1) 96 | if layer_nos is None: # layer_nos = None if invalid layer nos entered 97 | continue 98 | 99 | # Setting layers' visibility as asked 100 | Canvas_copy.SetLayersVisibility(layer_nos) 101 | 102 | if IsAborted: 103 | print("\nChoosing of layers aborted.\n") 104 | 105 | else: 106 | print("\nChoosing of layers successful.\n") 107 | Canvas_copy.Copy(copyTo=Canvas) 108 | 109 | cv2.destroyWindow(window_title) 110 | 111 | hf.Sleep() 112 | 113 | return 114 | 115 | 116 | def DeleteLayers(Canvas, window_title): 117 | # Storing initial layers data 118 | Canvas_copy = Canvas.Copy() 119 | 120 | # Checking if at least 1 layer is present so that it can be deleted. 121 | if len(Canvas_copy.layers) < 1: 122 | print("\nNot enough layers to delete. There should be atleast 1 layer.\n") 123 | return 124 | 125 | print("\nEnter the layer numbers (comma (',') separated) you wish to delete.") 126 | 127 | IsAborted = False 128 | while True: 129 | Canvas_copy.PrintLayerNames() 130 | # Showing layers 131 | Canvas_copy.Show(Title=window_title) 132 | cv2.waitKey(1) 133 | 134 | command = input("\nEnter 'Y'/'N' to confirm/abort deletion else enter any other key to continue: ") 135 | 136 | if 'y' in command or 'Y' in command: # if 'y'/'Y' entered -> Confirm deletion 137 | break 138 | 139 | elif 'n' in command or 'N' in command: # If 'n'/'N' entered -> Abort deletion 140 | IsAborted = True 141 | break 142 | 143 | # Asking for layer numbers cand checking if valid numbers passed. 144 | layer_nos = AskForLayerNumbers(0, len(Canvas_copy.layers) - 1) 145 | if layer_nos is None: # layer_nos = None if invalid layer nos entered 146 | continue 147 | 148 | # Ask again if less than 1 layer numbers entered. 149 | if len(layer_nos) < 1: 150 | print("Invalid number of layer numbers entered. Enter atleast 1 numbers.") 151 | continue 152 | 153 | # Delete layer corresponding to passed layer numbers. 154 | Canvas_copy.DeleteLayers(layer_nos) 155 | 156 | if IsAborted: 157 | print("\nDeleting of layers aborted.\n") 158 | 159 | else: 160 | print("\nDeleting of layers successful.\n") 161 | Canvas_copy.Copy(copyTo=Canvas) 162 | 163 | cv2.destroyWindow(window_title) 164 | 165 | 166 | 167 | def RearrangeLayers(Canvas, window_title): 168 | # Copying layer's data. 169 | Canvas_copy = Canvas.Copy() 170 | 171 | # Checking if at least 1 layer is present so that it can be deleted. 172 | if len(Canvas_copy.layers) < 2: 173 | print("\nNot enough layers to rearrange. There should be atleast 2 layer.\n") 174 | return 175 | 176 | print("\nEnter 2 comma(',') separated numbers of the layer you want to exchange.") 177 | 178 | IsAborted = False 179 | while True: 180 | Canvas_copy.PrintLayerNames() 181 | Canvas_copy.Show(Title=window_title) 182 | cv2.waitKey(1) 183 | 184 | command = input("\nEnter 'Y'/'N' to confirm/abort rearrangement else enter any other key to continue: ") 185 | 186 | if 'y' in command or 'Y' in command: # if 'y'/'Y' entered -> Confirm rearrange 187 | break 188 | 189 | elif 'n' in command or 'N' in command: # if 'n'/'N' entered -> Abort rearrange 190 | IsAborted = True 191 | break 192 | 193 | # Asking for layer numbers cand checking if valid numbers passed. 194 | layer_nos = AskForLayerNumbers(0, len(Canvas_copy.layers) - 1) 195 | if layer_nos is None: # layer_nos = None if invalid layer nos entered 196 | continue 197 | 198 | # If more or less than two layer numbers passed, ask again 199 | # Because 2 layer are exchanged in positions at a time. 200 | if len(layer_nos) != 2 : 201 | print("Invalid number of layer numbers entered. Enter exactly 2 numbers.") 202 | continue 203 | 204 | # Exchange layers. 205 | Canvas_copy.ExchangeLayers(layer_nos[0], layer_nos[1]) 206 | 207 | if IsAborted: 208 | print("\nRearranging of layers aborted.\n") 209 | 210 | else: 211 | print("\nRearranging of layers successful.\n") 212 | Canvas_copy.Copy(copyTo=Canvas) 213 | 214 | cv2.destroyWindow(window_title) 215 | 216 | 217 | def MergeLayers(Canvas, window_title): 218 | # Copying layer's data. 219 | Canvas_copy = Canvas.Copy() 220 | 221 | # Checking if at least 2 layers present. 222 | if len(Canvas_copy.layers) < 2: 223 | print("\nNot enough layers to merge. There should be atleast 2 layer.\n") 224 | return 225 | 226 | print("\nEnter comma(',') separated numbers of the layers you want to merge.") 227 | 228 | IsAborted = False 229 | while True: 230 | Canvas_copy.PrintLayerNames() 231 | Canvas_copy.Show(Title=window_title) 232 | cv2.waitKey(1) 233 | 234 | layer_nos = input("\nEnter 'Y'/'N' to confirm/abort rearrangement else enter any other key to continue: ") 235 | 236 | if 'y' in layer_nos or 'Y' in layer_nos: # if 'y'/'Y' entered -> Confirm merge 237 | break 238 | 239 | elif 'n' in layer_nos or 'N' in layer_nos: # if 'n'/'N' entered -> Abort merge 240 | IsAborted = True 241 | break 242 | 243 | # Asking for layer numbers and checking if valid numbers passed. 244 | layer_nos = AskForLayerNumbers(0, len(Canvas_copy.layers) - 1) 245 | if layer_nos is None: # layer_nos = None if invalid layer nos entered 246 | continue 247 | 248 | # Ask again if less than 2 layer numbers passed. 249 | # Because atleast 2 layers should be there to merge. 250 | if len(layer_nos) < 2: 251 | print("Invalid number of layer numbers entered. Enter atleast 2 numbers.") 252 | continue 253 | 254 | # Merge layers. 255 | Canvas_copy.MergeLayers(layer_nos) 256 | 257 | if IsAborted: 258 | print("\nMerging of layers aborted.\n") 259 | 260 | else: 261 | print("\nMerging of layers successful.\n") 262 | Canvas_copy.Copy(copyTo=Canvas) 263 | 264 | cv2.destroyWindow(window_title) 265 | 266 | 267 | def RenameLayers(Canvas): 268 | # Copying layer's data. 269 | Canvas_copy = Canvas.Copy() 270 | 271 | # Checking if at least 1 layer is present so that it can be renamed. 272 | if len(Canvas_copy.layers) < 1: 273 | print("\nNot enough layers to rename. There should be atleast 1 layer.\n") 274 | return 275 | 276 | print("\nEnter the layer number you wish to rename.") 277 | 278 | IsAborted = False 279 | while True: 280 | Canvas_copy.PrintLayerNames() 281 | 282 | command = input("\nEnter 'Y'/'N' to confirm/abort renaming else enter any other key to continue: ") 283 | 284 | if 'y' in command or 'Y' in command: # If 'y'/'Y' entered -> confirm rename 285 | break 286 | 287 | elif 'n' in command or 'N' in command: # if 'n'/'N' entered -> Abort rename 288 | IsAborted = True 289 | break 290 | 291 | # Ask for layer number to rename, if invalid layer number passed, ask again 292 | layer_no = AskForLayerNumbers(0, len(Canvas_copy.layers) - 1) 293 | if layer_no is None: # layer_nos = None if invalid layer nos entered 294 | continue 295 | 296 | # If more or less than 1 layer number entered, ask again. 297 | if len(layer_no) != 1: 298 | print("Invalid number of layer number entered. Enter exactly 1 number.") 299 | continue 300 | 301 | # Asking for new name 302 | rename_to = input("Enter the new name: ") 303 | # Renaming layer 304 | Canvas_copy.RenameLayer(layer_no[0], rename_to) 305 | 306 | if IsAborted: 307 | print("\nRenaming of layers aborted.\n") 308 | 309 | else: 310 | print("\nRenaming of layers successful.\n") 311 | Canvas_copy.Copy(copyTo=Canvas) 312 | 313 | 314 | 315 | def DuplicateLayers(Canvas): 316 | # Copying layer's data. 317 | Canvas_copy = Canvas.Copy() 318 | 319 | # Checking if at least 1 layer is present so that it can be renamed. 320 | if len(Canvas_copy.layers) < 1: 321 | print("\nNot enough layers to duplicate. There should be atleast 1 layer.\n") 322 | return 323 | 324 | print("\nEnter the layer number you wish to duplicate.") 325 | 326 | IsAborted = False 327 | while True: 328 | Canvas_copy.PrintLayerNames() 329 | 330 | command = input("\nEnter 'Y'/'N' to confirm/abort duplicating else enter any other key to continue: ") 331 | 332 | if 'y' in command or 'Y' in command: # If 'y'/'Y' entered -> confirm rename 333 | break 334 | 335 | elif 'n' in command or 'N' in command: # if 'n'/'N' entered -> Abort rename 336 | IsAborted = True 337 | break 338 | 339 | # Ask for layer number to rename, if invalid layer number passed, ask again 340 | layer_no = AskForLayerNumbers(0, len(Canvas_copy.layers) - 1) 341 | if layer_no is None: # layer_nos = None if invalid layer nos entered 342 | continue 343 | 344 | # If more or less than 1 layer number entered, ask again. 345 | if len(layer_no) != 1: 346 | print("Invalid number of layer number entered. Enter exactly 1 number.") 347 | continue 348 | 349 | # Duplicating layer 350 | Canvas_copy.DuplicateLayer(layer_no[0]) 351 | 352 | if IsAborted: 353 | print("\nDuplicating of layers aborted.\n") 354 | 355 | else: 356 | print("\nDuplicating of layers successful.\n") 357 | Canvas_copy.Copy(copyTo=Canvas) 358 | 359 | 360 | def LayerOperations(Canvas, window_title): 361 | while True: 362 | print() 363 | print("Enter 'R' to rearrange layers.") 364 | print("Enter 'D' to delete layers.") 365 | print("Enter 'M' to merge layers.") 366 | print("Enter 'E' to rename layers.") 367 | print("Enter 'C' to duplicate layers.") 368 | 369 | command = input("\nEnter command: ") 370 | command = command.replace(" ", "") 371 | 372 | if len(command) > 1: # If more than 1 command entered. 373 | print("Too many commands entered. Enter only one command.\n") 374 | continue 375 | 376 | elif 'r' in command or 'R' in command: # 'r'/'R' entered -> Rearrange layers 377 | RearrangeLayers(Canvas, window_title) 378 | break 379 | 380 | elif 'd' in command or 'D' in command: # 'd'/'D' entered -> Delete layers 381 | DeleteLayers(Canvas, window_title) 382 | break 383 | 384 | elif 'm' in command or 'M' in command: # 'm'/'M' entered -> Merge layers 385 | MergeLayers(Canvas, window_title) 386 | break 387 | 388 | elif 'e' in command or 'E' in command: # 'e'/'E' entered -> Rename layers 389 | RenameLayers(Canvas) 390 | break 391 | 392 | elif 'c' in command or 'C' in command: # 'c'/'C' entered -> Duplicate layer 393 | DuplicateLayers(Canvas) 394 | break 395 | 396 | else: # If invalid command is passed. 397 | print("Invalid command passed. Enter command again.\n") 398 | continue 399 | 400 | cv2.destroyWindow(window_title) 401 | hf.Sleep() 402 | 403 | return 404 | 405 | 406 | 407 | def MarqueeTool(Canvas, window_title): 408 | while True: 409 | print() 410 | print("Enter 'R' for Rectangular Marquee Tool.") 411 | print("Enter 'E' for Elliptical Marquee Tool.") 412 | print("Enter 'W' for Single Row Marquee Tool.") 413 | print("Enter 'C' for Single Column Marquee Tool.") 414 | 415 | command = input("\nEnter command: ") 416 | command = command.replace(" ", "") 417 | 418 | if len(command) > 1: # If more than 1 command entered. 419 | print("Too many commands entered. Enter only one command.\n") 420 | continue 421 | 422 | elif 'r' in command or 'R' in command: # 'r'/'R' entered -> Rectangular Marquee Tool 423 | marquee.RectangularMarqueeTool(Canvas, window_title) 424 | break 425 | 426 | elif 'e' in command or 'E' in command: # 'e'/'E' entered -> Elliptical Marquee Tool 427 | marquee.EllipticalMarqueeTool(Canvas, window_title) 428 | break 429 | 430 | elif 'w' in command or 'W' in command: # 'w'/'W' entered -> Single Row Marquee Tool 431 | marquee.SingleRowMarqueeTool(Canvas, window_title) 432 | break 433 | 434 | elif 'c' in command or 'C' in command: # 'c'/'C' entered -> Single Column Marquee Tool 435 | marquee.SingleColMarqueeTool(Canvas, window_title) 436 | break 437 | 438 | else: # If invalid command is passed. 439 | print("Invalid command passed. Enter command again.\n") 440 | continue 441 | 442 | hf.Sleep() 443 | 444 | return 445 | 446 | 447 | def LassoTool(Canvas, window_title): 448 | while True: 449 | print() 450 | print("Enter 'L' for Lasso Tool.") 451 | print("Enter 'P' for Polygon Lasso Tool.") 452 | print("Enter 'M' for Magnetic Lasso Tool.") 453 | 454 | command = input("\nEnter command: ") 455 | command = command.replace(" ", "") 456 | 457 | if len(command) > 1: # If more than 1 command entered. 458 | print("Too many commands entered. Enter only one command.\n") 459 | continue 460 | 461 | elif 'l' in command or 'L' in command: # 'l'/'L' entered -> Lasso Tool 462 | lasso.LassoTool(Canvas, window_title) 463 | break 464 | 465 | elif 'p' in command or 'P' in command: # 'p'/'P' entered -> Polygon Lasso Tool 466 | lasso.PolygonLassoTool(Canvas, window_title) 467 | break 468 | 469 | elif 'm' in command or 'M' in command: # 'm'/'M' entered -> Magnetic Lasso Tool 470 | lasso.MagneticLassoTool(Canvas, window_title) 471 | break 472 | 473 | else: # If invalid command is passed. 474 | print("Invalid command passed. Enter command again.\n") 475 | continue 476 | 477 | hf.Sleep() 478 | 479 | return 480 | 481 | 482 | def SelectionTool(Canvas, window_title): 483 | while True: 484 | print() 485 | print("Enter 'O' for Object Selection Tool.") 486 | print("Enter 'Q' for Quick Selection Tool.") 487 | print("Enter 'M' for Magic Wand Tool.") 488 | 489 | command = input("\nEnter command: ") 490 | command = command.replace(" ", "") 491 | 492 | if len(command) > 1: # If more than 1 command entered. 493 | print("Too many commands entered. Enter only one command.\n") 494 | continue 495 | 496 | elif 'o' in command or 'O' in command: # 'o'/'O' entered -> Object Selection Tool 497 | selection.ObjectSelectionTool(Canvas, window_title) 498 | break 499 | 500 | elif 'q' in command or 'Q' in command: # 'q'/'Q' entered -> Quick Selection Tool 501 | selection.QuickSelectionTool(Canvas, window_title) 502 | break 503 | 504 | elif 'm' in command or 'M' in command: # 'm'/'M' entered -> Magic Wand Tool 505 | selection.MagicWandTool(Canvas, window_title) 506 | break 507 | 508 | else: # If invalid command is passed. 509 | print("Invalid command passed. Enter command again.\n") 510 | continue 511 | 512 | hf.Sleep() 513 | 514 | return -------------------------------------------------------------------------------- /lasso.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import heapq 3 | import numpy as np 4 | 5 | import drawing 6 | import selectRegionClass 7 | import helping_functions as hf 8 | from selectRegionClass import AskLayerNumsToCopy, CropVisible, ExtractSelectedRegion 9 | 10 | 11 | 12 | ########################################################### Lasso Tool ################################################################################ 13 | 14 | class _LassoToolClass(selectRegionClass._SelectRegion): 15 | def __init__(self, Canvas, window_title, AskLayerNames=True, CorrectXYWhileSelecting=True, RegionMovable=True): 16 | super().__init__(Canvas, window_title, AskLayerNames=AskLayerNames, 17 | CorrectXYWhileSelecting=CorrectXYWhileSelecting, RegionMovable=RegionMovable) 18 | 19 | self.SelectedContour = [] 20 | 21 | # How to draw the region 22 | def DrawRegion(self): 23 | if not self.isSelected: 24 | drawing.Inc_Contour(self.FrameToShow, self.SelectedContour) 25 | else: 26 | drawing.Com_Contours(self.FrameToShow, [self.SelectedContour]) 27 | 28 | 29 | # When moue left button is pressed down 30 | def Mouse_EVENT_LBUTTONDOWN(self): 31 | self.SelectedContour = [] 32 | self.SelectedContour.append([self.x, self.y]) 33 | 34 | # When mouse is moved while selecting 35 | def Mouse_EVENT_MOUSEMOVE_selecting(self): 36 | self.SelectedContour.append([self.x, self.y]) 37 | 38 | # When mouse left button is released - check if something is selected 39 | def Mouse_EVENT_LBUTTONUP(self): 40 | if len(self.SelectedContour) <= 2: 41 | self.isSelected = False 42 | 43 | # When selected, move the region 44 | def Region_isSelected(self): 45 | if self.Key == 87 or self.Key == 119: # If 'W'/'w' - move up 46 | self.SelectedContour = hf.ShiftContour(self.SelectedContour, ToOrigin=False, ShiftBy=[0, -1]) 47 | elif self.Key == 65 or self.Key == 97: # If 'A'/'a' - move left 48 | self.SelectedContour = hf.ShiftContour(self.SelectedContour, ToOrigin=False, ShiftBy=[-1, 0]) 49 | elif self.Key == 83 or self.Key == 115: # If 'S'/'s' - move down 50 | self.SelectedContour = hf.ShiftContour(self.SelectedContour, ToOrigin=False, ShiftBy=[0, 1]) 51 | elif self.Key == 68 or self.Key == 100: # If 'D'/'d' - move right 52 | self.SelectedContour = hf.ShiftContour(self.SelectedContour, ToOrigin=False, ShiftBy=[1, 0]) 53 | 54 | # When region is selected and confirmed 55 | def GetSelectedRegionDetails(self): 56 | # Finding Selected regions bounding box, its contour shifted to origin, and its shifted mask image 57 | # Selected_BB = list(cv2.boundingRect(np.array(SelectedContour))) 58 | _, self.Selected_Mask, self.Selected_BB = hf.ShiftContour(self.SelectedContour, Get_Mask_BB=True) 59 | 60 | # Redrawing mask to conver any uncovered area 61 | OuterContour, _ = cv2.findContours(self.Selected_Mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 62 | cv2.drawContours(self.Selected_Mask, OuterContour, -1, 255, -1) 63 | 64 | 65 | def LassoTool(Canvas, window_title): 66 | ToolObject = _LassoToolClass(Canvas, window_title) 67 | ToolObject.RunTool() 68 | 69 | 70 | ####################################################################################################################################################### 71 | 72 | 73 | ########################################################### Polygon Lasso Tool ######################################################################## 74 | 75 | class _PolygonLassoToolClass(selectRegionClass._SelectRegion): 76 | def __init__(self, Canvas, window_title, AskLayerNames=True, CorrectXYWhileSelecting=True, RegionMovable=True): 77 | super().__init__(Canvas, window_title, AskLayerNames=AskLayerNames, 78 | CorrectXYWhileSelecting=CorrectXYWhileSelecting, RegionMovable=RegionMovable) 79 | 80 | self.Selected_Points = [] 81 | 82 | # How to draw the region 83 | def DrawRegion(self): 84 | if self.selecting: 85 | for i in range(len(self.Selected_Points)-1): 86 | drawing.LineAtAngle(self.FrameToShow, self.Selected_Points[i], self.Selected_Points[i+1], False) 87 | drawing.LineAtAngle(self.FrameToShow, self.Selected_Points[-1], [self.x, self.y], False) 88 | 89 | elif self.isSelected: 90 | for i in range(len(self.Selected_Points)): 91 | drawing.LineAtAngle(self.FrameToShow, self.Selected_Points[i], self.Selected_Points[i-1], True) 92 | 93 | # Callback function will be fully modified 94 | def CallBackFunc(self, event, x, y, flags, params): 95 | # If while selecting the region, mouse goes out of the frame, then clip it position 96 | # to the nearest corner/edge of the frame 97 | if self.selecting: 98 | self.x, self.y = hf.Correct_xy_While_Selecting(self.x, self.y, [0, self.CanvasShape[1]-1], [0, self.CanvasShape[0]-1]) 99 | 100 | # Storing mouse pointer values to self variable for access outside the function 101 | self.x, self.y = x, y 102 | 103 | # Starts selecting - Left button is pressed down 104 | if event == cv2.EVENT_FLAG_LBUTTON: 105 | self.selecting = True 106 | if self.isSelected: # If already selected, start drawing a new one 107 | self.isSelected = False 108 | self.Selected_Points = [] 109 | self.Selected_Points.append([x, y]) 110 | 111 | # Selecting the region 112 | elif event == cv2.EVENT_MOUSEMOVE: 113 | if self.selecting: 114 | self.SetCanvasFrame() 115 | 116 | # Stop selecting the layer. 117 | elif event == cv2.EVENT_LBUTTONDBLCLK: 118 | self.isSelected = True 119 | self.selecting = False 120 | if len(self.Selected_Points) <= 2: 121 | self.Selected_Points = [] 122 | self.isSelected = False 123 | else: 124 | self.Selected_Points.append([x, y]) 125 | self.SetCanvasFrame() 126 | 127 | # Move when region is selected 128 | def Region_isSelected(self): 129 | if self.Key == 87 or self.Key == 119: # If 'W'/'w' - move up 130 | self.Selected_Points = hf.ShiftContour(self.Selected_Points, ToOrigin=False, ShiftBy=[0, -1]) 131 | elif self.Key == 65 or self.Key == 97: # If 'A'/'a' - move left 132 | self.Selected_Points = hf.ShiftContour(self.Selected_Points, ToOrigin=False, ShiftBy=[-1, 0]) 133 | elif self.Key == 83 or self.Key == 115: # If 'S'/'s' - move down 134 | self.Selected_Points = hf.ShiftContour(self.Selected_Points, ToOrigin=False, ShiftBy=[0, 1]) 135 | elif self.Key == 68 or self.Key == 100: # If 'D'/'d' - move right 136 | self.Selected_Points = hf.ShiftContour(self.Selected_Points, ToOrigin=False, ShiftBy=[1, 0]) 137 | 138 | # Extracting selected regions BB and Mask 139 | def GetSelectedRegionDetails(self): 140 | # Finding Selected regions bounding box, its contour shifted to origin, and its shifted mask image 141 | # Selected_BB = list(cv2.boundingRect(np.array(SelectedContour))) 142 | _, self.Selected_Mask, self.Selected_BB = hf.ShiftContour(self.Selected_Points, Get_Mask_BB=True) 143 | 144 | # Redrawing mask to conver any uncovered area 145 | OuterContour, _ = cv2.findContours(self.Selected_Mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 146 | cv2.drawContours(self.Selected_Mask, OuterContour, -1, 255, -1) 147 | 148 | 149 | def PolygonLassoTool(Canvas, window_title): 150 | ToolObject = _PolygonLassoToolClass(Canvas, window_title) 151 | ToolObject.RunTool() 152 | 153 | ####################################################################################################################################################### 154 | 155 | 156 | ########################################################### Magnetic Lasso Tool ####################################################################### 157 | 158 | 159 | def Dij_SetROI(): 160 | global CombinedFrame, CanvasShape, dij_src_F, dij_end_F, RunningPoints_F, FinalPoints_F, Weights 161 | global ROI_Frame, ROI_Shape, dij_src_roi, dij_end_roi, ROI_Rect, ROI_Weights 162 | 163 | # Getting ROI's bounding rect 164 | ExtraROIBoundary = 10 165 | ROI_w = abs(dij_src_F[0] - dij_end_F[0]) + (ExtraROIBoundary * 2) 166 | ROI_h = abs(dij_src_F[1] - dij_end_F[1]) + (ExtraROIBoundary * 2) 167 | ROI_x = min(dij_src_F[0], dij_end_F[0]) - ExtraROIBoundary 168 | ROI_y = min(dij_src_F[1], dij_end_F[1]) - ExtraROIBoundary 169 | [ROI_x, ROI_y, ROI_w, ROI_h] = hf.Intersection([0, 0, CanvasShape[1], CanvasShape[0]], [ROI_x, ROI_y, ROI_w, ROI_h]) 170 | 171 | # Setting global variables 172 | ROI_Rect = [ROI_x, ROI_y, ROI_w, ROI_h] 173 | ROI_Shape = [ROI_h, ROI_w] 174 | ROI_Frame = CombinedFrame[ROI_y : ROI_y + ROI_h, ROI_x : ROI_x + ROI_w] 175 | dij_src_roi = [dij_src_F[0] - ROI_x, dij_src_F[1] - ROI_y] 176 | dij_end_roi = [dij_end_F[0] - ROI_x, dij_end_F[1] - ROI_y] 177 | ROI_Weights = np.asarray(Weights)[ : , ROI_y : ROI_y + ROI_h, ROI_x : ROI_x + ROI_w] 178 | 179 | 180 | 181 | def Dij_SetWeights(): 182 | global Weights, CombinedFrame 183 | Weights = [None] * 9 184 | 185 | # Storing the weights of each neighbours in list of length 9 186 | # [0 1 2] 187 | # [3 4 5] 188 | # [6 7 8] 189 | Kernels = [None] * 9 190 | 191 | Kernels[0] = np.array([[ 0, 0.7, 0], 192 | [ -0.7, 0, 0], 193 | [ 0, 0, 0]], dtype=np.float32) 194 | Kernels[1] = np.array([[-0.25, 0, 0.25], 195 | [-0.25, 0, 0.25], 196 | [ 0, 0, 0]], dtype=np.float32) 197 | Kernels[2] = np.array([[ 0, 0.7, 0], 198 | [ 0, 0, -0.7], 199 | [ 0, 0, 0]], dtype=np.float32) 200 | Kernels[3] = np.array([[ 0.25, 0.25, 0], 201 | [ 0, 0, 0], 202 | [-0.25, -0.25, 0]], dtype=np.float32) 203 | Kernels[4] = np.array([[ 0, 0, 0], 204 | [ 0, 10**6, 0], 205 | [ 0, 0, 0]], dtype=np.float32) 206 | Kernels[5] = np.array([[ 0, -0.25, -0.25], 207 | [ 0, 0, 0], 208 | [ 0, 0.25, 0.25]], dtype=np.float32) 209 | Kernels[6] = np.array([[ 0, 0, 0], 210 | [ -0.7, 0, 0], 211 | [ 0, 0.7, 0]], dtype=np.float32) 212 | Kernels[7] = np.array([[ 0, 0, 0], 213 | [ 0.25, 0, -0.25], 214 | [ 0.25, 0, -0.25]], dtype=np.float32) 215 | Kernels[8] = np.array([[ 0, 0, 0], 216 | [ 0, 0, 0.7], 217 | [ 0, -0.7, 0]], dtype=np.float32) 218 | 219 | 220 | # Finding weights 221 | #CombinedFrame = cv2.blur(CombinedFrame, (3, 3)) 222 | for i in range(9): 223 | # Applying convolution 224 | # Temp will be 3 channeled image 225 | Temp = cv2.filter2D(CombinedFrame, -1, Kernels[i]) 226 | 227 | # Merging the channels to get weights as: B^2 + G^2 + R^2 + 0.01 228 | # This will ensure that weights are positive and non zero (For Dijsktra's algo) 229 | # Compliment of B, G, R will be taken to support larger differences 230 | B, G, R = cv2.split(Temp) 231 | B = 255 - B 232 | G = 255 - G 233 | R = 255 - R 234 | Weights[i] = cv2.max(255 - (B*B + G*G + R*R + 0.01), 0) 235 | 236 | 237 | 238 | def ExtractParentPath(dij_end_roi, Parent): 239 | # Shortest path 240 | Path = [] 241 | 242 | currentPt = [dij_end_roi[0], dij_end_roi[1]] 243 | while currentPt[0] != -1: 244 | # Adding this point to path 245 | Path.append(currentPt) 246 | 247 | # Getting parent and updating current point 248 | currentPt = Parent[currentPt[1]][currentPt[0]].copy() 249 | 250 | # Reversing the path (to get from src to end) 251 | Path.reverse() 252 | 253 | return Path 254 | 255 | 256 | def RunningPoints_to_frame(InitialPoints, f_x, f_y): 257 | FinalPoints = [] 258 | for i in range(len(InitialPoints)): 259 | FinalPoints.append([InitialPoints[i][0] + f_x, InitialPoints[i][1] + f_y]) 260 | 261 | return FinalPoints 262 | 263 | 264 | 265 | def Dij_ShortestPath(): 266 | global dij_src_F, dij_end_F, Weights, CanvasShape, RunningPoints_F, \ 267 | dij_src_roi, dij_end_roi, ROI_Shape, ROI_Rect, RunningPoints_roi, ROI_Weights 268 | 269 | # If dij_src_F and dij_end_F are neighbours - directly update running points 270 | if abs(dij_src_F[0] - dij_end_F[0]) <= 1 and abs(dij_src_F[1] - dij_end_F[1]) <= 1: 271 | if dij_src_F[0] == dij_end_F[0] and dij_src_F[1] == dij_end_F[1]: 272 | RunningPoints_F = [[dij_src_F[0], dij_src_F[1]]] 273 | else: 274 | RunningPoints_F = [[dij_src_F[0], dij_src_F[1]], 275 | [dij_end_F[0], dij_end_F[1]]] 276 | return 277 | 278 | # Setting Weights of neighbours 279 | if Weights is None: 280 | Dij_SetWeights() 281 | 282 | # Setting ROI for Dijsktra's 283 | Dij_SetROI() 284 | 285 | # 1 if the node is visited, 0 if the node is not visited 286 | IsVisited = np.zeros((ROI_Shape[0], ROI_Shape[1], 1), dtype=bool) 287 | 288 | # Distances of the points from source 289 | Distances = np.ones((ROI_Shape[0], ROI_Shape[1], 1), dtype=np.float32) * 100000000.0 290 | Distances[dij_src_roi[1]][dij_src_roi[0]] = 0 # Distance of source to source is zero 291 | 292 | # Parents of all the points 293 | # [-1, -1] for no parent (source node) 294 | Parent = [[[-1, -1] for j in range(ROI_Shape[1])] for i in range(ROI_Shape[0])] 295 | 296 | 297 | # Initializing priority queue 298 | PQueue = [] 299 | 300 | # Current node 301 | [currX, currY] = dij_src_roi 302 | 303 | # Finding shortest path for all vertices 304 | while True: 305 | # Setting current node as visited 306 | IsVisited[currY][currX] = True 307 | 308 | # Loop through all neighbours 309 | for i in range(-1, 2, 1): 310 | for j in range(-1, 2, 1): 311 | # Continue if the neighbour is already visited 312 | if IsVisited[currY + i][currX + j]: 313 | continue 314 | 315 | # Finding new and old distances of the newghbour 316 | OldDist = Distances[currY + i][currX + j] 317 | NewDist = Distances[currY][currX] + ROI_Weights[(i+1)*3 + (j+1)][currY][currX] 318 | 319 | # if new distance is lesser than old distance 320 | if NewDist < OldDist: 321 | # Updating distance 322 | Distances[currY + i][currX + j] = NewDist 323 | 324 | # Updating parent of this neighbour is the current point 325 | Parent[currY + i][currX + j] = [currX, currY] 326 | 327 | # Pushing this neighbour to priority Queue 328 | if not IsVisited[currY + i][currX + j] and \ 329 | 0 < (currX + j) < (ROI_Shape[1] - 1) and \ 330 | 0 < (currY + i) < (ROI_Shape[0] - 1): 331 | heapq.heappush(PQueue, (NewDist, currX + j, currY + i)) 332 | 333 | #### End of updating neighbours loop 334 | 335 | # Break if priority queue is empty 336 | if len(PQueue) == 0: 337 | break 338 | 339 | # Finding the minimum distance element in priority queue, 340 | # check if it is visited, 341 | # if not, remove it and update currX&Y 342 | minPQEle = heapq.heappop(PQueue) 343 | while IsVisited[minPQEle[2]][minPQEle[1]]: 344 | try: 345 | minPQEle = heapq.heappop(PQueue) 346 | except IndexError: 347 | break 348 | 349 | currX, currY = minPQEle[1], minPQEle[2] 350 | 351 | 352 | # Getting the shortest path from src to end 353 | RunningPoints_roi = ExtractParentPath(dij_end_roi, Parent) 354 | 355 | # Converting Running point from wrt roi to frame 356 | RunningPoints_F = RunningPoints_to_frame(RunningPoints_roi, ROI_Rect[0], ROI_Rect[1]) 357 | 358 | 359 | 360 | def DrawPoints(Image, Points, Colour=[127, 127, 127]): 361 | for i in range(len(Points)): 362 | Image[Points[i][1]][Points[i][0]] = Colour 363 | 364 | return Image 365 | 366 | 367 | def DrawPointsOnFrame(): 368 | global FrameToShow, CombinedFrame, RunningPoints_F, FinalPoints_F 369 | 370 | # Drawing points 371 | FrameToShow = CombinedFrame.copy() 372 | FrameToShow = DrawPoints(FrameToShow, FinalPoints_F, Colour=[0, 255, 0]) 373 | FrameToShow = DrawPoints(FrameToShow, RunningPoints_F, Colour=[0, 0, 255]) 374 | 375 | 376 | def CallBackFunc_MagLassoTool(event, x, y, flags, params): 377 | # Taking global params 378 | global selecting, isSelected, CombinedFrame, FrameToShow, CanvasShape, SelectedContour, \ 379 | dij_src_F, dij_end_F, RunningPoints_F, FinalPoints_F, RunningPoints_roi 380 | 381 | # If while selecting the region, mouse goes out of the frame, then clip it position 382 | # to the nearest corner/edge of the frame 383 | if selecting: 384 | x, y = hf.Correct_xy_While_Selecting(x, y, [0, CanvasShape[1]-1], [0, CanvasShape[0]-1]) 385 | 386 | # Setting dijsktra's end point to mouse cursor's current coordinate 387 | dij_end_F = [x, y] 388 | 389 | # Starts selecting - Left button is pressed down 390 | if event == cv2.EVENT_FLAG_LBUTTON: 391 | if isSelected: 392 | isSelected = False 393 | selecting = True 394 | dij_src_F = [x, y] 395 | RunningPoints_F = [] 396 | RunningPoints_roi = [] 397 | FinalPoints_F = [] 398 | SelectedContour = [] 399 | 400 | else: 401 | if not selecting: 402 | selecting = True 403 | dij_src_F = [x, y] 404 | RunningPoints_F = [] 405 | RunningPoints_roi = [] 406 | FinalPoints_F = [] 407 | 408 | else: 409 | # Add shortest path to final points 410 | FinalPoints_F += RunningPoints_F[:-15] 411 | dij_src_F = RunningPoints_F[-15]#[x, y] 412 | 413 | # Selecting the region 414 | elif event == cv2.EVENT_MOUSEMOVE: 415 | if selecting: 416 | # Call dijsktra's 417 | Dij_ShortestPath() 418 | # Draw selected and running 419 | DrawPointsOnFrame() 420 | 421 | 422 | # Stop selecting the layer. 423 | elif event == cv2.EVENT_LBUTTONDBLCLK: 424 | isSelected = True 425 | selecting = False 426 | # Check final points size here 427 | if len(FinalPoints_F) <= 2: 428 | FinalPoints_F = [] 429 | isSelected = False 430 | 431 | # Add last running points to final points 432 | FinalPoints_F += RunningPoints_F 433 | # Convert finalPoints to Selected Contour 434 | SelectedContour = FinalPoints_F.copy() 435 | # Draw contour 436 | FrameToShow = CombinedFrame.copy() 437 | cv2.drawContours(FrameToShow, [np.array(SelectedContour)], -1, (127, 127, 127), 1) 438 | 439 | 440 | def MagneticLassoTool(Canvas, window_title): 441 | hf.Clear() 442 | # Taking layer numbers user wants to copy 443 | Canvas.PrintLayerNames() 444 | if len(Canvas.layers) <= 1: 445 | layer_nos_to_copy = [-1] 446 | print("\nThe tool will copy the only layer present.") 447 | else: 448 | layer_nos_to_copy = AskLayerNumsToCopy(-1, len(Canvas.layers) - 1) 449 | 450 | print("\nPress 'Y' to confirm selection and copy it in a new layer else press 'N' to abort.") 451 | print("You can also used the keys 'W', 'A', 'S', and 'D', to move the") 452 | print("selected region Up, Left, Down, and Right respectively.") 453 | 454 | # Clearing mouse buffer data (old mouse data) - this is a bug in OpenCV probably 455 | cv2.namedWindow(window_title) 456 | cv2.setMouseCallback(window_title, hf.EmptyCallBackFunc) 457 | Canvas.Show(Title=window_title) 458 | cv2.waitKey(1) 459 | 460 | # Setting mouse callback 461 | cv2.setMouseCallback(window_title, CallBackFunc_MagLassoTool) 462 | 463 | # Setting some params used in callback function 464 | global selecting, isSelected, CombinedFrame, FrameToShow, CanvasShape, SelectedContour, \ 465 | dij_src_F, dij_end_F, RunningPoints_F, FinalPoints_F, Weights, \ 466 | ROI_Frame, ROI_Shape, dij_src_roi, dij_end_roi, ROI_Rect, RunningPoints_roi, ROI_Weights 467 | selecting = False # True if region is being selected 468 | isSelected = False # True if region is selected 469 | Canvas.CombineLayers() 470 | CombinedFrame = Canvas.CombinedImage.copy() # the combined frame of the canvas 471 | FrameToShow = CombinedFrame.copy() # The frame which will be shown (with the selected region) 472 | CanvasShape = Canvas.Shape # Shape of the canvas 473 | SelectedContour = [] # Contour of the selected region 474 | RunningPoints_F = [] # The points that are being selected 475 | FinalPoints_F = [] # The points that are finalized 476 | dij_src_F = None # Strat point of dijstra's algo 477 | dij_end_F = None # End point of dijstra's algo 478 | Weights = None # Weights of all the neighbours for each pixel in the image 479 | # Same params wrt the ROI 480 | ROI_Frame, ROI_Shape, dij_src_roi, dij_end_roi, ROI_Rect, ROI_Weights = None, None, None, None, None, None 481 | RunningPoints_roi = [] 482 | 483 | IsAborted = False 484 | while True: 485 | # Showing canvas 486 | cv2.imshow(window_title, FrameToShow) 487 | Key = cv2.waitKey(1) 488 | 489 | if Key == 8: # If Backspace pressed 490 | if len(FinalPoints_F) > 1: 491 | PoppedEle = FinalPoints_F.pop() 492 | dij_src_F = PoppedEle 493 | RunningPoints_F.insert(0, PoppedEle) 494 | DrawPointsOnFrame() 495 | 496 | if Key == 89 or Key == 121: # If 'Y'/'y' - confirm 497 | if isSelected: # If the region is selected 498 | break 499 | else: # If the region is not selected yet 500 | print("\nSelect a region first to confirm.") 501 | continue 502 | elif Key == 78 or Key == 110: # If 'N'/'n' - abort 503 | IsAborted = True 504 | break 505 | 506 | # If the region is selected, check if the user is trying to move it 507 | if isSelected: 508 | if Key == 87 or Key == 119: # If 'W'/'w' - move up 509 | SelectedContour = hf.ShiftContour(SelectedContour, ToOrigin=False, ShiftBy=[0, -1]) 510 | if Key == 65 or Key == 97: # If 'A'/'a' - move left 511 | SelectedContour = hf.ShiftContour(SelectedContour, ToOrigin=False, ShiftBy=[-1, 0]) 512 | if Key == 83 or Key == 115: # If 'S'/'s' - move down 513 | SelectedContour = hf.ShiftContour(SelectedContour, ToOrigin=False, ShiftBy=[0, 1]) 514 | if Key == 68 or Key == 100: # If 'D'/'d' - move right 515 | SelectedContour = hf.ShiftContour(SelectedContour, ToOrigin=False, ShiftBy=[1, 0]) 516 | 517 | FrameToShow = CombinedFrame.copy() 518 | drawing.Com_Contours(FrameToShow, [SelectedContour]) 519 | 520 | 521 | if not IsAborted: 522 | # Finding Selected regions bounding box, its contour shifted to origin, and its shifted mask image 523 | SelectedContourToOrigin, Selected_Mask, Selected_BB = hf.ShiftContour(SelectedContour, Get_Mask_BB=True) 524 | 525 | # Redrawing mask to conver any uncovered area 526 | OuterContour, _ = cv2.findContours(Selected_Mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 527 | cv2.drawContours(Selected_Mask, OuterContour, -1, 255, -1) 528 | 529 | # Extracting the selected regions and copying them in a new layer 530 | ExtractSelectedRegion(Canvas, Selected_BB, Selected_Mask, layer_nos_to_copy) 531 | 532 | else: 533 | print("\nRegion selection aborted.") 534 | 535 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------