OpenCV Python – Mouse Events

OpenCV Python – Handling Mouse Events ”; Previous Next OpenCV is capable of registering various mouse related events with a callback function. This is done to initiate a certain user defined action depending on the type of mouse event. Sr.No Mouse event & Description 1 cv.EVENT_MOUSEMOVE When the mouse pointer has moved over the window. 2 cv.EVENT_LBUTTONDOWN Indicates that the left mouse button is pressed. 3 cv.EVENT_RBUTTONDOWN Event of that the right mouse button is pressed. 4 cv.EVENT_MBUTTONDOWN Indicates that the middle mouse button is pressed. 5 cv.EVENT_LBUTTONUP When the left mouse button is released. 6 cv.EVENT_RBUTTONUP When the right mouse button is released. 7 cv.EVENT_MBUTTONUP Indicates that the middle mouse button is released. 8 cv.EVENT_LBUTTONDBLCLK This event occurs when the left mouse button is double clicked. 9 cv.EVENT_RBUTTONDBLCLK Indicates that the right mouse button is double clicked. 10 cv.EVENT_MBUTTONDBLCLK Indicates that the middle mouse button is double clicked. 11 cv.EVENT_MOUSEWHEEL Positive for forward and negative for backward scrolling. To fire a function on a mouse event, it has to be registered with the help of setMouseCallback() function. The command for the same is as follows − cv2.setMouseCallback(window, callbak_function) This function passes the type and location of the event to the callback function for further processing. Example 1 Following code draws a circle whenever left button double click event occurs on the window showing an image as background − import numpy as np import cv2 as cv # mouse callback function def drawfunction(event,x,y,flags,param): if event == cv.EVENT_LBUTTONDBLCLK: cv.circle(img,(x,y),20,(255,255,255),-1) img = cv.imread(”lena.jpg”) cv.namedWindow(”image”) cv.setMouseCallback(”image”,drawfunction) while(1): cv.imshow(”image”,img) key=cv.waitKey(1) if key == 27: break cv.destroyAllWindows() Output Run the above program and double click at random locations. The similar output will appear − Example 2 Following program interactively draws either rectangle, line or circle depending on user input (1,2 or 3) − import numpy as np import cv2 as cv # mouse callback function drawing=True shape=”r” def draw_circle(event,x,y,flags,param): global x1,x2 if event == cv.EVENT_LBUTTONDOWN: drawing = True x1,x2 = x,y elif event == cv.EVENT_LBUTTONUP: drawing = False if shape == ”r”: cv.rectangle(img,(x1,x2),(x,y),(0,255,0),-1) if shape == ”l”: cv.line(img,(x1,x2),(x,y),(255,255,255),3) if shape==”c”: cv.circle(img,(x,y), 10, (255,255,0), -1) img = cv.imread(”lena.jpg”) cv.namedWindow(”image”) cv.setMouseCallback(”image”,draw_circle) while(1): cv.imshow(”image”,img) key=cv.waitKey(1) if key==ord(”1”): shape=”r” if key==ord(”2”): shape=”l” if key==ord(”3”): shape=”c” #print (shape) if key == 27: break cv.destroyAllWindows() On the window surface, a rectangle is drawn between the coordinates of the mouse left button down and up if ‘1’ is pressed. If user choice is 2, a line is drawn using coordinates as endpoints. On choosing 3 for the circle, it is drawn at the coordinates of the mouse up event. Following image will be the output after the successful execution of the above mentioned program − Print Page Previous Next Advertisements ”;

OpenCV Python – Image Properties

OpenCV Python – Image Properties ”; Previous Next OpenCV reads the image data in a NumPy array. The shape() method of this ndarray object reveals image properties such as dimensions and channels. The command to use the shape() method is as follows − >>> img = cv.imread(“OpenCV_Logo.png”, 1) >>> img.shape (222, 180, 3) In the above command − The first two items shape[0] and shape[1] represent width and height of the image. Shape[2] stands for a number of channels. 3 indicates that the image has Red Green Blue (RGB) channels. Similarly, the size property returns the size of the image. The command for the size of an image is as follows − >>> img.size 119880 Each element in the ndarray represents one image pixel. We can access and manipulate any pixel’s value, with the help of the command mentioned below. >>> p=img[50,50] >>> p array([ 1, 1, 255], dtype=uint8) Example Following code changes the color value of the first 100X100 pixels to black. The imshow() function can verify the result. >>> for i in range(100): for j in range(100): img[i,j]=[0,0,0] Output The image channels can be split in individual planes by using the split() function. The channels can be merged by using merge() function. The split() function returns a multi-channel array. We can use the following command to split the image channels − >>> img = cv.imread(“OpenCV_Logo.png”, 1) >>> b,g,r = cv.split(img) You can now perform manipulation on each plane. Suppose we set all pixels in blue channel to 0, the code will be as follows − >>> img[:, :, 0]=0 >>> cv.imshow(“image”, img) The resultant image will be shown as below − Print Page Previous Next Advertisements ”;

OpenCV Python – Image Filtering

OpenCV Python – Image Filtering ”; Previous Next An image is basically a matrix of pixels represented by binary values between 0 to 255 corresponding to gray values. A color image will be a three dimensional matrix with a number of channels corresponding to RGB. Image filtering is a process of averaging the pixel values so as to alter the shade, brightness, contrast etc. of the original image. By applying a low pass filter, we can remove any noise in the image. High pass filters help in detecting the edges. The OpenCV library provides cv2.filter2D() function. It performs convolution of the original image by a kernel of a square matrix of size 3X3 or 5X5 etc. Convolution slides a kernel matrix across the image matrix horizontally and vertically. For each placement, add all pixels under the kernel, take the average of pixels under the kernel and replace the central pixel with the average value. Perform this operation for all pixels to obtain the output image pixel matrix. Refer the diagram given below − The cv2.filter2D() function requires input array, kernel matrix and output array parameters. Example Following figure uses this function to obtain an averaged image as a result of 2D convolution. The program for the same is as follows − import numpy as np import cv2 as cv from matplotlib import pyplot as plt img = cv.imread(”opencv_logo_gs.png”) kernel = np.ones((3,3),np.float32)/9 dst = cv.filter2D(img,-1,kernel) plt.subplot(121),plt.imshow(img),plt.title(”Original”) plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(dst),plt.title(”Convolved”) plt.xticks([]), plt.yticks([]) plt.show() Output Types of Filtering Function Other types of filtering function in OpenCV includes − BilateralFilter − Reduces unwanted noise keeping edges intact. BoxFilter − This is an average blurring operation. GaussianBlur − Eliminates high frequency content such as noise and edges. MedianBlur − Instead of average, it takes the median of all pixels under the kernel and replaces the central value. Print Page Previous Next Advertisements ”;

OpenCV Python – Bitwise Operations

OpenCV Python – Bitwise Operations ”; Previous Next Bitwise operations are used in image manipulation and for extracting the essential parts in the image. Following operators are implemented in OpenCV − bitwise_and bitwise_or bitwise_xor bitwise_not Example 1 To demonstrate the use of these operators, two images with filled and empty circles are taken. Following program demonstrates the use of bitwise operators in OpenCV-Python − import cv2 import numpy as np img1 = cv2.imread(”a.png”) img2 = cv2.imread(”b.png”) dest1 = cv2.bitwise_and(img2, img1, mask = None) dest2 = cv2.bitwise_or(img2, img1, mask = None) dest3 = cv2.bitwise_xor(img1, img2, mask = None) cv2.imshow(”A”, img1) cv2.imshow(”B”, img2) cv2.imshow(”AND”, dest1) cv2.imshow(”OR”, dest2) cv2.imshow(”XOR”, dest3) cv2.imshow(”NOT A”, cv2.bitwise_not(img1)) cv2.imshow(”NOT B”, cv2.bitwise_not(img2)) if cv2.waitKey(0) & 0xff == 27: cv2.destroyAllWindows() Output Example 2 In another example involving bitwise operations, the opencv logo is superimposed on another image. Here, we obtain a mask array calling threshold() function on the logo and perform AND operation between them. Similarly, by NOT operation, we get an inverse mask. Also, we get AND with the background image. Following is the program which determines the use of bitwise operations − import cv2 as cv import numpy as np img1 = cv.imread(”lena.jpg”) img2 = cv.imread(”whitelogo.png”) rows,cols,channels = img2.shape roi = img1[0:rows, 0:cols] img2gray = cv.cvtColor(img2,cv.COLOR_BGR2GRAY) ret, mask = cv.threshold(img2gray, 10, 255, cv.THRESH_BINARY) mask_inv = cv.bitwise_not(mask) # Now black-out the area of logo img1_bg = cv.bitwise_and(roi,roi,mask = mask_inv) # Take only region of logo from logo image. img2_fg = cv.bitwise_and(img2,img2,mask = mask) # Put logo in ROI dst = cv.add(img2_fg, img1_bg) img1[0:rows, 0:cols ] = dst cv.imshow(Result,img1) cv.waitKey(0) cv.destroyAllWindows() Output The masked images give following result − Print Page Previous Next Advertisements ”;

OpenCV Python – Histogram

OpenCV Python – Histogram ”; Previous Next Histogram shows the intensity distribution in an image. It plots the pixel values (0 to 255) on X axis and number of pixels on Y axis. By using histogram, one can understand the contrast, brightness and intensity distribution of the specified image. The bins in a histogram represent incremental parts of the values on X axis. In our case, it is the pixel value and the default bin size is one. In OpenCV library, the function cv2.calcHist() function which computes the histogram from the input image. The command for the function is as follows − cv.calcHist(images, channels, mask, histSize, ranges) Parameters The cv2.calcHist() function’s parameters are as follows − images − It is the source image of type uint8 or float32, in square brackets, i.e., “[img]”. channels − It is the index of the channel for which we calculate histogram. For a grayscale image, its value is [0]. For BGR images, you can pass [0], [1] or [2] to calculate the histogram of each channel. mask − Mask image is given as “None” for full image. For a particular region of image, you have to create a mask image for that and give it as a mask. histSize − This represents our BIN count. ranges − Normally, it is [0,256]. Histogram using Matplotlib A histogram plot can be obtained either with the help of Matplotlib’s pyplot.plot() function or by calling Polylines() function from OpenCV library. Example Following program computes histogram for each channel in the image (lena.jpg) and plots the intensity distribution for each channel − import numpy as np import cv2 as cv from matplotlib import pyplot as plt img = cv.imread(”lena.jpg”) color = (”b”,”g”,”r”) for i,col in enumerate(color): hist = cv.calcHist([img],[i],None,[256],[0,256]) plt.plot(hist, color = col) plt.xlim([0,256]) plt.show() Output Print Page Previous Next Advertisements ”;