image processing with python – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Thu, 28 Oct 2021 11:52:34 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 image processing with python – Java2Blog https://java2blog.com 32 32 Python | Introduction and Installation of OpenCv https://java2blog.com/python-introduction-installation-opencv/?utm_source=rss&utm_medium=rss&utm_campaign=python-introduction-installation-opencv https://java2blog.com/python-introduction-installation-opencv/#respond Sun, 09 Aug 2020 17:45:16 +0000 https://java2blog.com/?p=9852 In this tutorial, we are learning about what is OpenCv and how OpenCV is installed in windows/linux system.

Introduction

Have you ever seen Facebook’s auto-tag feature? Whenever you add an image on Facebook, it consequently labels those who are there within the image. Ever considered how that occurred. It happens all as a result of Computer Vision. OpenCv is a library which is utilized to recognize faces and distinguish them. Facebook’s auto-tag feature is one of the many examples where face recognition algorithm is used. Another instance is face unlock characteristic in our mobile phones. This feature uses Computer Vision to pick out and confirm humans by analyzing the unique features of their face.

Computer Vision

Computer Vision is a field that includes a technique for procuring, preparing, analyzing, and understanding images and finding concealed data in the picture. It copies the capacities of human vision by electronically perceiving and understanding an image
In the simplest terms, computer vision is the discipline of "teaching machines how to see."

It is a field of artificial intelligence that trains computers to decipher and comprehend the visual world. Utilizing pictures from cameras and recordings and deep learning models, machines can precisely recognize and characterize objects — and afterwards, respond to what they "see."

How computer vision works ?
Computer vision works in three basic steps:

1) Acquiring an image

Pictures, even huge sets, can be procured progressively through video, photographs or 3D technology for analysis.

2) Processing the image

Deep learning models automate lots of this process, however, the models are frequently trained by first being fed hundreds of categorized or pre-recognized pictures.

3) Understanding the image

The final step is the interpretative step, in which an object is identified or classified.

Applications

1) Sports – Hawk Eye

Hawk-Eye is a computer machine used in several sports together with cricket, tennis, etc., to visually observe the trajectory of the ball and display a profile of its statistically most likely direction as a shifting image.

2) Smart cars

Computer Vision in independent vehicles can prompt the planning and improvement of cutting edge and next-gen vehicles that could conquer riding limitations while guarding travellers. Such automobiles can delivery passengers to their destination wiping out human mediation.

OpenCV

OpenCV is the enormous open-source library for the computer vision, AI, and image processing and now it plays a main position in real-time operation which is very essential in today’s systems. By the usage of it, you’ll be able to process images and motion pictures to perceive objects, faces, or even handwriting of a human. When it included with various libraries, together with Numpy, python is capable of processing the OpenCV array structure for analysis. To Identify image pattern and its various features we use vector space and perform mathematical operations on these features.

The first OpenCV version was 1.0. OpenCV is launched beneath a BSD license and subsequently, it’s free for both educational and industrial use. It has C++, C, Python and Java interfaces and supports Windows, Linux, Mac OS, iOS and Android. When OpenCV was designed the primary focus was real-time applications for computational efficiency. Everything is written in optimized C/C++ to take advantage of multi-core processing.

To install OpenCV, one must have Python and PIP, preinstalled on their system. To check if your system already contains Python, go through the following instructions:

Insall openCV on windows and linux

If you are using Windows then open the Command line(search for cmd in the Run dialogue (Windows Symbol + R). Or else open terminal in Ubuntu with Open the Ctrl+Alt+T
Now run the following command:

Python --version

If Python is already installed, it will show a message with the Python version available.

PIP is the standard package manager for Python. We can use pip to install extra packages that are not available in the Python standard library.
PIP comes pre-installed on the Python versions 3.4 or older. To check if PIP is already installed on your system, just go to the command line and execute the following command:

pip --version

Downloading and Installing OpenCV:

To install OpenCV, just go to the command-line and type the following command:

pip install opencv-python #for python2
pip3 install opencv-python #for python3

To check if OpenCV is correctly installed, just run the following commands to perform a version check:

· python
· >>>import cv2
· >>>print(cv2.__version__)

If you are using Anaconda in that case:
Open the anaconda command prompt and type in below command.

conda install –c menpo opencv3

That’s all about introduction and installation of opencv in Python.

]]>
https://java2blog.com/python-introduction-installation-opencv/feed/ 0
Python | cv2 imshow() Method https://java2blog.com/cv2-imshow-python/?utm_source=rss&utm_medium=rss&utm_campaign=cv2-imshow-python https://java2blog.com/cv2-imshow-python/#respond Sun, 09 Aug 2020 17:36:56 +0000 https://java2blog.com/?p=9763 In this tutorial, we will see how to display an image as an output using python by the use of open-cv which is exist as cv2 (computer vision) library.

We can use imshow() method of cv2 library to display an image in a window. In order to use cv2 library, we need to import cv2 library using import statement.

Now let’s see the syntax and return value of cv2 imshow() method, then we will move on the examples.

Syntax

cv2.imshow(win_name,image)

Parameters

You need to pass two parameters to imwrite() method. Parameters are:
1) win_name: Name of the window in which the image will be displayed.
2) image: Image pixel matrix of that image, which will need to be shown.

Return Value

None

Return value

Let’s see the python code :

# import computer vision library(cv2) in this code
import cv2

# main code
if __name__ == "__main__" :

    # mentioning absolute path of the image
    img_path = "C:\\Users\\user\\Desktop\\flower.jpg"

    # read or load an image
    image = cv2.imread(img_path)

    # show the image on the newly created image window
    cv2.imshow('image window',image)

Output :

Output1

As you can see, a window is opened to display the image. Window size is dependent on size of the image. If window size is greater than screen resolution, then it displays scaled version of the image.

]]>
https://java2blog.com/cv2-imshow-python/feed/ 0
Python | cv2 imwrite() Method https://java2blog.com/cv2-imwrite-python/?utm_source=rss&utm_medium=rss&utm_campaign=cv2-imwrite-python https://java2blog.com/cv2-imwrite-python/#respond Sun, 09 Aug 2020 17:34:55 +0000 https://java2blog.com/?p=9772 In this tutorial, we will see how to save an image in your own system using python by using open-cv which exists as cv2 (computer vision) library.

You can use imwrite() method of cv2 library to save an image on your system. To use cv2 library, you need to import cv2 library using import statement.

Now let’s see the syntax and return value of imwrite() method, then we will move on to the examples.

Syntax

cv2.imwrite(path, image)

Parameters

You need to pass two parameters to imwrite() method. Parameters are:

  1. path: Location address where you want to save an image in your system in string form with including the filename.

    here two cases will be possible :

    i) if you want to save an image in the current working directory then we have to mention only the name of the image with their extension like .jpg,.png etc.

    ii) if you want to save an image at somewhere else in your system not in the current working directory then we have to give complete path, also known as, absolute path of the image.

  2. image: It is the image pixel matrix of that image, which you want to save in your system.

Return Value

It returns either True or False. Return True if the image is successfully saved otherwise return False.

cv2 imwrite() method Examples

Now Let’s see the Python code :

# import computer vision library(cv2) in this Program
import cv2

# import os library in this program
import os

# main code
if __name__ == "__main__" :

    # mentioning absolute path of the image
    img_path = "C:\\Users\\user\\Desktop\\flower.jpg"

    # read an image
    image = cv2.imread(img_path)

    print("Before saving an image ,contents of directory shows :")

    # shows the contents of given directory
    print(os.listdir("C:\\Users\\user\\Desktop\\save image"))
    
    # mentioning absolute path 
    save_img_path = "C:\\Users\\user\\Desktop\\save image\\image1.jpg"
    
    # save an image at the given mention path
    cv2.imwrite(save_img_path,image)

    print("After saving an image ,contents of directory shows :")

    # shows the contents of given directory
    print(os.listdir("C:\\Users\\user\\Desktop\\save image"))

Output :

Before saving an image, contents of directory shows :
[] After saving an image, contents of directory shows :
[‘image1.jpg’]

That’s all about cv2.imwrite() Method.

]]>
https://java2blog.com/cv2-imwrite-python/feed/ 0
Python | cv2 findContours() Method https://java2blog.com/cv2-findcontours-python/?utm_source=rss&utm_medium=rss&utm_campaign=cv2-findcontours-python https://java2blog.com/cv2-findcontours-python/#respond Sat, 23 May 2020 11:12:15 +0000 https://java2blog.com/?p=10064 In this tutorial, we will see how to find all boundary points(x,y) of an object in the image using python open-cv, which exists as cv2 (computer vision) library.
You can use findContours() method of cv2 library to find all boundary points(x,y) of an object in the image. To use cv2 library, you need to import cv2 library using import statement.

Contours can be explained simply as a curve joining all the continuous points (along the boundary), having the same color or intensity. The contours are very useful for shape analysis and object recognition and object detection.

Note:
For better accuracy, we must use binary images. So before finding contours, apply threshold or canny edge detection on the input image.

Now let’s see the syntax and return value of cv2 findContours() method first, then we will move on to the examples.

Syntax

cv2.findContours(src, contour_retrieval, contours_approximation)

Parameters

You need to pass three parameters to findContours() method.

  1. src: Input Image of n – dimensional array(n = 2,3) but preferred 2-dim binary images for better result.
  2. contour_retrieval: This is contour retrieval mode. Possible values are :
    a) cv2.RETR_TREE
    b) cv2.RETR_EXTERNAL
    c) cv2.RETR_LIST
    d) cv2.RETR_CCOMP etc.
  3. contours_approximation: This is Contour approximation method. Possible values are :
    a) cv2.CHAIN_APPROX_NONE
    b) cv2.CHAIN_APPROX_SIMPLE

Return Value

It returns three values :
a) Input image array
b) Contours
c) Hierarchy

Note:
1) Contours is a Python list of all the contours in the image. Each individual contour is a Numpy array of (x,y) coordinates of boundary points of the object.

2) Hierarchy is the parent-child relationship in contours. It is represented as an array of four values : [Next contour, previous contour, First child contour, Parent contour]

If you are interested in reading more about Hierarchy,Contour Retrieval Mode then click on this given link hierarchy and contours retrieval mode

Contours Approximation Method

Above, we see that contours are the boundaries of a shape with the same intensity. It stores the (x, y) coordinates of the boundary of a shape. But does it store all the coordinates? That is specified by this contour approximation method.
If we pass cv2.CHAIN_APPROX_NONE, all the boundary points are captured. But actually, do we need all the points? For eg, if we need find the contour of a straight line. We require just two endpoints of that line. In that case, you can pass cv2.CHAIN_APPROX_SIMPLE. It excludes all excessive points and compresses the contour, thereby saving memory.

cv2 findContours() Method examples

Now Let’s see the Python code:

Example 1: Using cv2.RETR_TREE as a retrieval mode and cv2.CHAIN_APPROX_NONE as a Contour approximation method.

# import computer vision library(cv2) in this code
import cv2

# main code
if __name__ == "__main__" :

    # mentioning absolute path of the image
    img_path = "C:\\Users\\user\\Desktop\\rectangle.jpg"

    # read/load an image in grayscale mode
    image = cv2.imread(img_path,0)

    # show the Input image on the newly created image window
    cv2.imshow('Input',image)

    # applying cv2.THRESH_BINARY thresholding techniques
    ret, bin_img = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)

    # show the binary image on the newly created image window
    cv2.imshow('Intermediate',bin_img)

    # extracting the contours from the given binary image
    img,contours, hierarchy = cv2.findContours(bin_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

    print("Total Number of Contours found =", len(contours))
    print("contours are: \n",contours)
    print("hierarchy is: \n",hierarchy)
Output :
output1

Total Number of Contours found = 5
contours are:
[array([[[0, 0]],[[0, 1]],

[[0, 2]],

…,

[[3, 0]],

[[2, 0]],

[[1, 0]]], dtype=int32), array([[[202, 35]],

[[203, 34]],

[[204, 35]],

[[203, 36]]], dtype=int32), array([[[183, 35]],

[[184, 34]],

[[185, 34]],

[[186, 34]],

[[187, 34]],

[[188, 34]],

[[189, 34]],

[[190, 34]],

[[191, 34]],

[[192, 35]],

[[191, 36]],

[[190, 36]],

[[189, 36]],

[[188, 36]],

[[187, 36]],

[[186, 36]],

[[185, 36]],

[[184, 36]]], dtype=int32), array([[[49, 35]],

[[50, 34]],

[[51, 34]],

[[52, 34]],

[[53, 35]],

[[52, 36]],

[[51, 36]],

[[51, 37]],

[[50, 38]],

[[49, 37]],

[[49, 36]]], dtype=int32), array([[[46, 32]],

[[47, 31]],

[[48, 31]],

…,

[[46, 35]],

[[46, 34]],

[[46, 33]]], dtype=int32)] hierarchy is:
[[[-1 -1 1 -1] [ 2 -1 -1 0] [ 3 1 -1 0] [ 4 2 -1 0] [-1 3 -1 0]]]

Example 2: Using cv2.RETR_EXTERNAL as a Contour retrieval mode and cv2.CHAIN_APPROX_SIMPLE as a Contour approximation method.

# import computer vision library(cv2) in this code
import cv2

# main code
if __name__ == "__main__" :

    # mentioning absolute path of the image
    img_path = "C:\\Users\\user\\Desktop\\rectangle.jpg"

    # read/load an image in grayscale mode
    image = cv2.imread(img_path,0)

    # show the Input image on the newly created image window
    cv2.imshow('Input',image)

    # applying cv2.THRESH_BINARY thresholding techniques
    ret, bin_img = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)

    # show the binary image on the newly created image window
    cv2.imshow('Intermediate',bin_img)

    # extracting the contours from the given binary image
    img,contours, hierarchy = cv2.findContours(bin_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    print("Total Number of Contours found =", len(contours))

    print("contours are: \n",contours)
    print("hierarchy is: \n",hierarchy)
Output :
output1

Total Number of Contours found = 1
contours are:
[array([[[ 0, 0]],[[ 0, 191]],

[[261, 191]],

[[261, 0]]], dtype=int32)] hierarchy is:

[[[-1 -1 -1 -1]]]

Reference

OpenCV python Contours tutorial

That’s all about cv2 findContours() Method.

]]>
https://java2blog.com/cv2-findcontours-python/feed/ 0
Python | cv2 threshold() Method https://java2blog.com/cv2-threshold-python/?utm_source=rss&utm_medium=rss&utm_campaign=cv2-threshold-python https://java2blog.com/cv2-threshold-python/#respond Sat, 23 May 2020 10:29:36 +0000 https://java2blog.com/?p=10031 In this tutorial, we will see how to separate an object from the background in the image using python open-cv, which exists as cv2 (computer vision) library.
You can use threshold() method of cv2 library to separate an object from the background in the image. To use cv2 library, you need to import cv2 library using import statement.

Now let’s see the syntax and return value of cv2 threshold() method first, then we will move on the examples.

Syntax

cv2.threshold(src, thresholdValue, maxVal, thresholdingTechnique)

Parameters

You need to pass four parameters to cv2 threshold() method.

  1. src:Input Grayscale Image array.
  2. thresholdValue: Mention that value which is used to classify the pixel values.
  3. maxVal: The value to be given if pixel value is more than (sometimes less than) the threshold value.
  4. thresholdingTechnique: The type of thresholding to be applied.
  5. There are 5 different simple thresholding techniques are :

    1. cv2.THRESH_BINARY: If pixel intensity is greater than the set threshold, value set to 255, else set to 0 (black).
    2. cv2.THRESH_BINARY_INV: Inverted or Opposite case of cv2.THRESH_BINARY.<li.
    3. cv2.THRESH_TRUNC: If pixel intensity value is greater than threshold, it is truncated to the threshold. The pixel values are set to be the same as the threshold. All other values remain the same.
    4. cv2.THRESH_TOZERO: Pixel intensity is set to 0, for all the pixels intensity, less than the threshold value.
    5. cv2.THRESH_TOZERO_INV: Inverted or Opposite case of cv2.THRESH_TOZERO.

Return Value

This method return a tuple of 2 values in which 1st value is given threshold value and 2nd value is modified image array.

cv2 threshold() Method examples

Now Let’s see the Python code :

Example 1: Using cv2.THRESH_BINARY thresholding technique.

# import computer vision library(cv2) in this code
import cv2

# main code
if __name__ == "__main__" :

    # mentioning absolute path of the image
    img_path = "C:\\Users\\user\\Desktop\\flower.jpg"

    # read/load an image in grayscale mode
    grey_img = cv2.imread(img_path,0)

    # show the Input image on the newly created image window
    cv2.imshow('Input',grey_img)

    # applying cv2.THRESH_BINARY thresholding techniques
    ret, thresh_img = cv2.threshold(grey_img, 128, 255, cv2.THRESH_BINARY)

    # show the Output image on the newly created image window
    cv2.imshow('Output',thresh_img)

Output:

Output1

Example 2 : Using cv2.THRESH_BINARY_INV thresholding technique.

# import computer vision library(cv2) in this code
import cv2

# main code
if __name__ == "__main__" :

    # mentioning absolute path of the image
    img_path = "C:\\Users\\user\\Desktop\\flower.jpg"

    # read/load an image in grayscale mode
    grey_img = cv2.imread(img_path,0)

    # show the Input image on the newly created image window
    cv2.imshow('Input',grey_img)

    # applying cv2.THRESH_BINARY_INV thresholding techniques
    ret, thresh_img = cv2.threshold(grey_img, 128, 255, cv2.THRESH_BINARY_INV)

    # show the Output image on the newly created image window
    cv2.imshow('Output',thresh_img)

Output:

output2

Similarly, you can apply other given thresholding techniques and see their results.

That’s all about cv2 threshold() Method.

]]>
https://java2blog.com/cv2-threshold-python/feed/ 0
Python | cv2 VideoCapture() method https://java2blog.com/cv2-videocapture-python/?utm_source=rss&utm_medium=rss&utm_campaign=cv2-videocapture-python https://java2blog.com/cv2-videocapture-python/#comments Sat, 23 May 2020 10:18:00 +0000 https://java2blog.com/?p=9976 In this tutorial, we will see how to read a video and start a webcam using python open-cv, which exists as cv2 (computer vision) library.
You can use VideoCapture() method of cv2 library to read and start live streaming. To use cv2 library, you need to import cv2 library using import statement.

Now let’s see the syntax and return value of cv2 canny() method first, then we will move on to the examples.

Syntax

cv2.VideoCapture(video_path or device index )

Parameters

There is one argument which needs to pass in VideoCapture() class.

video_path: Locationvideo in your system in string form with their extensions like .mp4, .avi, etc.

OR

device index: It is just the number to specify the camera. Its possible values ie either 0 or -1.

Return value

Video capture object.

cv2 VideoCapture() method examples

Now Let’s see the Python code :

Example 1: Run a given video file.

# import computer vision library(cv2) in this code
import cv2

# main code
if __name__ == "__main__" :

    # mentioning absolute path of the video
    video_path = "C:\\Users\\user\\Desktop\\test_video.mp4"

    # creating a video capture object
    video_object = cv2.VideoCapture(video_path)

    # handling errors
    # if any erros is occured during the running of the program
    # then it handles
    try :
        # run a infinite loop 
        while(True) :

            # read a video frame by frame
            # read() returns tuple in which 1st item is boolean value 
            # either True or False and 2nd item is frame of the video.
            # read() returns False when video is ended so 
            # no frame is readed and error will be generated.
            ret,frame = video_object.read()
            
            # show the frame on the newly created image window
            cv2.imshow('Frames',frame)

            # this condition is used to run a frames at the interval of 10 mili sec
            # and if in b/w the frame running , any one want to stop the execution .
            if cv2.waitKey(10) & 0xFF == ord('q') :

                # break out of the while loop
                break

    except :
        # if any error occurs then this block of code will run
        print("Video has ended..")
Output :
output1

Example 2: Start a webcam.

# import computer vision library(cv2) in this code
import cv2

# main code
if __name__ == "__main__" :

    # creating a video capture object
    # argument 0 , webcam start
    video_object = cv2.VideoCapture(0)

    # handling errors
    # if any erros is occured during the running of the program
    # then it handles
    try :
        # run a infinite loop 
        while(True) :

            # read a video frame by frame
            # read() returns tuple in which 1st item is boolean value 
            # either True or False and 2nd item is frame of the video.
            # read() returns False when live video is ended so 
            # no frame is readed and error will be generated.
            ret,frame = video_object.read()
            
            # show the frame on the newly created image window
            cv2.imshow('Frames',frame)

            # this condition is used to run a frames at the interval of 10 mili sec
            # and if in b/w the frame running , any one want to stop the execution .
            if cv2.waitKey(10) & 0xFF == ord('q') :

                # break out of the while loop
                break

    except :
        # if error occur then this block of code is run
        print("Video has ended..")
Output:
output2

That’s all about Python cv2 VideoCapture() method,

]]>
https://java2blog.com/cv2-videocapture-python/feed/ 1
Python | cv2 cvtColor() Method https://java2blog.com/cv2-cvtcolor-python/?utm_source=rss&utm_medium=rss&utm_campaign=cv2-cvtcolor-python https://java2blog.com/cv2-cvtcolor-python/#respond Sat, 23 May 2020 09:53:20 +0000 https://java2blog.com/?p=9842 In this tutorial, we will see how to change the color of an image from one color space to another using python open-cv, which exists as cv2 (computer vision) library.
You can use cvtColor() method of cv2 library to convert the color of an image from one color space to another. To use cv2 library, you need to import cv2 library using import statement.

There are more than 150 shading space transformation techniques accessible in OpenCV. In any case, we will investigate just two which are most broadly utilized ones, BGR Gray and BGR HSV.

BGR –> Blue Green Red
HSV –> Hue Saturation Values

Note :
1) For BGR, Blue,Green,Red value range is [0,255] 2) For HSV, Hue range is [0,179], Saturation range is [0,255] and Value range is [0,255].

Now let’s see the syntax and return value of cv2 cvtColor() the method first, then we will move on to the examples.

Syntax

cv2.cvtColor(image, code, dst, dstCn)

Parameters

You can pass four parameters to cvtColor() method. Among the four parameters, the first 2(image and code) are mandatory; rest(dst and dstCn) are optional.

    1. Necessary parameters are:

    2. image: Source/Input image of n-dimensional array.
    3. code: Conversion code for color space.

Optional parameters are:

  1. dst: Output image of the same size and depth as source.
  2. dstCn: The number of channels in the destination image. If you put parameter as 0, the number of the channels is obtained automatically from image and code.

Return Value :

It returns the Coverted color space image.

The default color format in OpenCV is often referred to as RGB, but it is actually BGR (the bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on.

cv2 cvtColor() Method examples

Now Let’s see the Python code :

Example 1: Convert image from BGR color space to GRAY color space.

# import computer vision library(cv2) in this code
import cv2

# main code
if __name__ == "__main__" :

    # mentioning absolute path of the image
    img_path = "C:\\Users\\user\\Desktop\\flower.jpg"

    # read/load an image
    image = cv2.imread(img_path)

    # show the input image on the newly created window
    cv2.imshow('input image',image)

    # convert image from BGR color space to GRAY color space
    convert_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY )

    # show the output image on the newly created window
    cv2.imshow('output image',convert_image)
Output:
output1

Example 2: Convert image from BGR color space to HSV color space.

# import computer vision library(cv2) in this code
import cv2

# main code
if __name__ == "__main__" :

    # mentioning absolute path of the image
    img_path = "C:\\Users\\user\\Desktop\\flower.jpg"

    # read/load an image
    image = cv2.imread(img_path)

    # show the input image on the newly created window
    cv2.imshow('input image',image)

    # convert image from BGR color space to HSV color space
    convert_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

    # show the output image on the newly created window
    cv2.imshow('output image',convert_image)
Output:
output2

Source

https://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html
That’s all about Python cv2 cvtColor() Method.

]]>
https://java2blog.com/cv2-cvtcolor-python/feed/ 0
Python | cv2 Canny() Method https://java2blog.com/cv2-canny-python/?utm_source=rss&utm_medium=rss&utm_campaign=cv2-canny-python https://java2blog.com/cv2-canny-python/#respond Fri, 15 May 2020 13:36:33 +0000 https://java2blog.com/?p=9816 In this tutorial, we will see how to detect edges in the image using python open-cv, which exists as cv2 (computer vision) library.

You can use Canny() method of cv2 library to detect edges in an image. To use cv2 library, you need to import cv2 library using import statement.

Canny() method uses canny edge detection algorithm for finding the edges in the image.

For more information: canny edge detection algorithm

Now let’s see the syntax and return value of cv2 canny() method first, then we will move on the examples.

Syntax

cv2.Canny(image, threshold1, threshold2, apertureSize, L2gradient)

Parameters

You can pass five parameters to resize() method. Among the five parameters, the first three(image,threshold ,and threshold2) are mandatory; rest(apertureSize and L2gradient) are optional.

    Necessary parameters are:

  1. image: Source/Input image of n-dimensional array.
  2. threshold1: It is the High threshold value of intensity gradient.
  3. threshold2: It is the Low threshold value of intensity gradient.
  4. Optional parameters are:

  5. apertureSize: Order of Kernel(matrix) for the Sobel filter. Its default value is (3 x 3), and its value should be odd between 3 and 7. It is used for finding image gradients. Filter is used for smoothening and sharpening of an image.
  6. L2gradient: This specifies the equation for finding gradient magnitude. L2gradient is of boolean type, and its default value is False.

Return Value

It returns Grayscale edge detected image.

cv2 Canny() Method example

Now Let’s see the Python code :
Example 1: Using Canny() method with necessary parameters only.

# import computer vision library(cv2) in this code
import cv2

# main code
if __name__ == "__main__" :

    # mentioning absolute path of the image
    img_path = "C:\\Users\\user\\Desktop\\flower.jpg"

    # read/load an image
    image = cv2.imread(img_path)

    # show the input image on the newly created image window
    cv2.imshow('image window1',image)

    # detection of the edges
    img_edge = cv2.Canny(image,100,200)

    # show the image edges on the newly created image window
    cv2.imshow('image window2',img_edge)

Output:

output1

Example 2: Using Canny() method with apertureSize parameter value along with necessary parameters.

# import computer vision library(cv2) in this code
import cv2

# main code
if __name__ == "__main__" :

    # mentioning absolute path of the image
    img_path = "C:\\Users\\user\\Desktop\\flower.jpg"

    # read/load an image
    image = cv2.imread(img_path)

    # show the input image on the newly created image window
    cv2.imshow('image window1',image)

    # detection of the edges
    img_edge = cv2.Canny(image,100,200,apertureSize = 5)

    # show the image edges on the newly created image window
    cv2.imshow('image window2',img_edge)

Output :

output11

Example 3: Using Canny() method with L2gradient and apertureSize parameter values along with necessary parameters.

# import computer vision library(cv2) in this code
import cv2

# main code
if __name__ == "__main__" :

    # mentioning absolute path of the image
    img_path = "C:\\Users\\user\\Desktop\\flower.jpg"

    # read/load an image
    image = cv2.imread(img_path)

    # show the input image on the newly created image window
    cv2.imshow('image window1',image)

    # detection of the edges
    img_edge = cv2.Canny(image,100,200,apertureSize = 5, L2gradient = True)

    # show the image edges on the newly created image window
    cv2.imshow('image window2',img_edge)

Output:

output12

Example 4: Using Canny() method with L2gradient parameter value along with necessary parameters.

# import computer vision library(cv2) in this code
import cv2

# main code
if __name__ == "__main__" :

    # mentioning absolute path of the image
    img_path = "C:\\Users\\user\\Desktop\\flower.jpg"

    # read/load an image
    image = cv2.imread(img_path)

    # show the input image on the newly created image window
    cv2.imshow('image window1',image)

    # detection of the edges
    img_edge = cv2.Canny(image,100,200, L2gradient = True)

    # show the image edges on the newly created image window
    cv2.imshow('image window2',img_edge)

Output:

s13

That’s all about cv2 Canny() Method in Python.

]]>
https://java2blog.com/cv2-canny-python/feed/ 0
Python | cv2 GaussianBlur() Method https://java2blog.com/cv2-gaussianblur-python/?utm_source=rss&utm_medium=rss&utm_campaign=cv2-gaussianblur-python https://java2blog.com/cv2-gaussianblur-python/#respond Fri, 15 May 2020 13:23:02 +0000 https://java2blog.com/?p=9804 In this tutorial, we will see how to Blurring an image in python programming language using open-cv, which exists as a cv2 (computer vision) library in python.

You can use GaussianBlur() method of cv2 library to blur an image. In order to use cv2 library, you need to import cv2 library using import statement. You can read about more about Gaussian function

The blurring of an image means smoothening of an image i.e., removing outlier pixels that may be noise in the image.

Now let’s see the syntax and return value of GaussianBlur() method, then we will move on the examples.

Syntax

cv2.GaussianBlur(src, ksize, sigmaX, sigmaY, borderType)

Parameters

  1. src: Source/Input of n-dimensional array.
  2. ksize: Kernal is matrix of an (no. of rows)*(no. of columns) order .Its Size is given in the form of tuple (no. of rows, no. of columns). no. of rows and no. of columns should be odd .If ksize is given as (0 0), then ksize is computed from given sigma values i.e. sigmaX and sigmaY.
  3. sigmaX: Standard deviation value of kernal along horizontal direction.
  4. sigmaY: Standard deviation value of kernal along vertical direction.
  5. borderType: This specify boundaries of an image while kernel is applied on borders of an image.
  6. Possible values of borderType are :

    1. cv2.BORDER_CONSTANT
    2. cv2.BORDER_REPLICATE
    3. cv2.BORDER_REFLECT
    4. cv2.BORDER_WRAP
    5. cv2.BORDER_REFLECT_101
    6. cv2.BORDER_TRANSPARENT
    7. cv2.BORDER_REFLECT101
    8. cv2.BORDER_DEFAULT
    9. cv2.BORDER_ISOLATED

Return Value

It returns Output blurred image of n-dimensional array.

a) In GaussianBlur() method, you need to pass src and ksize values everytime and either one, two, or all parameters value from remaining sigmax, sigmaY and borderType parameter should be passed.

b) Both sigmaX and sigmaY parameters become optional if you mention the ksize(kernal size) value other than (0,0).

cv2 GaussianBlur() Method example

Now Let’s see the Python code :

Example 1: Using GaussianBlur() method with src,ksize and borderType parameters.

# import computer vision library(cv2) in this code
import cv2

# main code
if __name__ == "__main__" :

    # mentioning absolute path of the image
    img_path = "C:\\Users\\user\\Desktop\\flower.jpg"

    # Load/Read an image
    image = cv2.imread(img_path)

    # show the image on the newly created image window
    cv2.imshow('Input image',image)

    # applying gaussian blur on the image
    blur_img = cv2.GaussianBlur(image,(5,5),cv2.BORDER_DEFAULT)

    # show the image on the newly created image window
    cv2.imshow('Blur image',blur_img)

Output :

Output1

Example 2: Using GaussianBlur() method with src,ksize and sigmaX parameters.

# import computer vision library(cv2) in this code
import cv2

# main code
if __name__ == "__main__" :

    # mentioning absolute path of the image
    img_path = "C:\\Users\\user\\Desktop\\flower.jpg"

    # Load/Read an image
    image = cv2.imread(img_path)

    # show the image on the newly created image window
    cv2.imshow('Input image',image)

    # applying gaussian blur on the image with kernal size(5,5)
    # and sigmaX = 5
    blur_img = cv2.GaussianBlur(image,(5,5),5)

    # show the image on the newly created image window
    cv2.imshow('Blur image',blur_img)

Output :

Output2

You may similarly change the values of other properties and observe the outputs.
That’s all about cv2 GaussianBlur() Method in Python.

]]>
https://java2blog.com/cv2-gaussianblur-python/feed/ 0