Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
OpenCV C++ Program to create a single colored blank image
Next article icon

OpenCV C++ Program to blur an image

Last Updated : 19 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

The following is the explanation to the C++ code to blur an Image in C++ using the tool OpenCV. 
Things to know: 
(1) The code will only compile in Linux environment. 
(2) Compile command: g++ -w article.cpp -o article `pkg-config –libs opencv` 
(3) Run command: ./article 
(4) The image bat.jpg has to be in the same directory as the code. 
Before you run the code, please make sure that you have OpenCV installed on your system. 
 

// Title: OpenCV C++ Program to blur an image.  // Import the core header file  #include <opencv2/core/core.hpp>     // core - a compact module defining basic data structures,  // including the dense multi-dimensional array Mat and   // basic functions used by  all other modules.    // highgui - an easy-to-use interface to video   // capturing, image and video codecs, as well  // as simple UI capabilities.  #include <opencv2/highgui/highgui.hpp>    // imgproc - an image processing module that   // includes linear and non-linear image filtering,  // geometrical image transformations (resize, affine  // and perspective warping, generic table-based   // remapping) color space conversion, histograms,   // and so on.  #include <opencv2/imgproc/imgproc.hpp>    // The stdio.h header defines three variable types,   // several macros, and various functions for performing  // input and output.  #include <stdio.h>  #include <iostream>    // Namespace where all the C++ OpenCV functionality resides  using namespace cv;    using namespace std;    // We can also use 'namespace std' if need be.    int main() // Main function  {      // read the image data in the file "MyPic.JPG" and       // store it in 'img'      Mat image = imread("bat.jpg", CV_LOAD_IMAGE_UNCHANGED);            // Mat object is a basic image container.      // imread: first argument denotes the image to be loaded      // the second arguments specifies the image format.      // CV_LOAD_IMAGE_UNCHANGED (<0) loads the image as is      // CV_LOAD_IMAGE_GRAYSCALE ( 0) loads the image as an      //                         intensity one      // CV_LOAD_IMAGE_COLOR (>0) loads the image in the       //                          BGR format      // If the second argument is not specified, it is       // implied CV_LOAD_IMAGE_COLOR        // Check for no data      if (! image.data )       {          cout << "Could not open or find the image.\n";          return -1; // unsuccessful      }         // Function to blur the image      // first argument: input source      // second argument: output source      // third argument: blurring kernel size      blur(image,image,Size(10,10));         // Create a window      // first argument: name of the window      // second argument: flag- types:      // WINDOW_NORMAL If this is set, the user can resize the       //                window.      // WINDOW_AUTOSIZE If this is set, the window size is       //                 automatically adjusted to fit the       //                 displayed image() ), and you cannot       //                 change the window size manually.      // WINDOW_OPENGL If this is set, the window will be      //              created with OpenGL support.      namedWindow( "bat", CV_WINDOW_AUTOSIZE );         // Displays an image in the specified window.      // first argument: name of the window      // second argument: image to be shown(Mat object)      imshow( "bat", image );         waitKey(0); // Wait infinite time for a keypress            return 0; // Return from the main function  }

 To Run the program in the Windows, VISUAL STUDIO  you can use following approach:

The idea is to first use a function called cvtColor  to convert the input image into Grayscale image, then we will convert that Grayscale image to Blurred Image using a function GaussianBlur.

SYNTAX:  

cvtColor(source_image, destination_image, code);

GaussianBlur(source_image, destination_image, kernel-size, sigmaX);

PARAMETERS:

cvtColor is the in-built function in the C++ that is used to convert one color space(number of channels) to another using the color space conversion code. Color space conversion code are easily accessible and are pre-defined. You can learn more about them over here.

GaussianBlur takes Grayscale image as input and returns a blurred image.  

Kernel size is used to define how much we want the kernel to affect the pixels in our image. Now kernel is the matrix of pixels in the image, so when we define kernel size it will first pickup an anchor(a center point) and then it will affect the pixels in its neighborhood. In a 3*3 matrix only the neighborhood pixel’s will be affected while in a 10*10 matrix will affect the pixels in range of 10*10 matrix from the center.

SigmaX: A variable of the type double representing the Gaussian kernel standard deviation in X direction.

Implementation of the above approach.

C++




#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
  
using namespace std;
using namespace cv;
  
void main() // we can use int main as well just don't forget
            // to add return 0 in the end
{
    string path = "Resources/face.jpeg";
    Mat img = imread(path);
   
    Mat imgGray, Blur_img;    //Defining Output Image matrix
  
    cvtColor(img, imgGray,
             COLOR_BGR2GRAY); // To convert image to
                              // grayscale image
    GaussianBlur(img, Blur_img, Size(7, 7), 5,
                 0); // Now finally adding blur to the image
  
    imshow("Image", img); // Image before the conversion
    imshow("GrayImage",imgGray); // After Conversion to GrayScale
    imshow("Blurimg", Blur_img); // Blurred Image
  
    waitKey(0); // wait for keystroke
}
 
 

OUTPUT:

Original image

GrayScale Image:

GrayImage

Blur Image:

Blurred Image

OpenCV Python Program to Blur Image 
 

About the Author: 

 

Aditya Prakash is an undergraduate student at Indian Institute 

Aditya

of Information Technology, Vadodara. He primarily codes in C++. The motto for him is: So far so good. He plays cricket, watches superhero movies, football and is a big fan of answering questions.

 

If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks.

 
 



Next Article
OpenCV C++ Program to create a single colored blank image
author
kartik
Improve
Article Tags :
  • C++
  • Project
  • Image-Processing
Practice Tags :
  • CPP

Similar Reads

  • OpenCV C++ Program to blur a Video
    The following is the explanation to the C++ code to blur a video in C++ using the tool OpenCV. Things to know: (1) The code will only compile in Linux environment. (2) To run in windows, please use the file: 'blur_video.o' and run it in cmd. However if it does not run(problem in system architecture)
    3 min read
  • OpenCV C++ Program to create a single colored blank image
    The following is the explanation to the C++ code to create a single colored blank image in C++ using the tool OpenCV. Things to know:  (1) The code will only compile in Linux environment. (2) To run in windows, please use the file: 'blank.o' and run it in cmd. However if it does not run (problem in
    3 min read
  • OpenCV - Blur image
    In this article, we will learn how to Blur an image using Python OpenCV. [GFGTABS] Python </p><pre><code class="language-python3"># Python Program to blur image import cv2 # bat.jpg is the batman image. img = cv2.imread('bat.jpg') # make sure that you have saved i
    2 min read
  • Python OpenCV | cv2.blur() method
    OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.blur() method is used to blur an image using the normalized box filter. The function smooths an image using the kernel which is represented as: Syntax: cv2.blur(src, ksize[, dst[, anchor[, borderType]]]) Pa
    2 min read
  • OpenCV C++ Program to play a video
    The following is the explanation to the C++ code to play a video in C++ using the tool OpenCV. Things to know: (1) The code will only compile in Linux environment. (2) To run in windows, please use the file: 'play_video.o' and run it in cmd. However if it does not run(problem in system architecture)
    3 min read
  • OpenCV Python Program to analyze an image using Histogram
    In this article, image analysis using Matplotlib and OpenCV is discussed. Let's first understand how to experiment image data with various styles and how to represent with Histogram. Prerequisites: OpenCVmatplotlibImporting image data import matplotlib.pyplot as plt #importing matplotlib The image s
    4 min read
  • Python | Image blurring using OpenCV
    Image Blurring refers to making the image less clear or distinct. It is done with the help of various low pass filter kernels. Advantages of blurring: It helps in Noise removal. As noise is considered as high pass signal so by the application of low pass filter kernel we restrict noise. It helps in
    2 min read
  • OpenCV | Saving an Image
    This article aims to learn how to save an image from one location to any other desired location on your system in CPP using OpenCv. Using OpenCV, we can generate a blank image with any colour one wishes to. So, let us dig deep into it and understand the concept with the complete explanation. Code :
    3 min read
  • Cpp14 Program to Turn an image by 90 degree
    Given an image, how will you turn it by 90 degrees? A vague question. Minimize the browser and try your solution before going further. An image can be treated as 2D matrix which can be stored in a buffer. We are provided with matrix dimensions and it's base address. How can we turn it? For example s
    4 min read
  • Reading an image in OpenCV using Python
    Prerequisite: Basics of OpenCV In this article, we'll try to open an image by using OpenCV (Open Source Computer Vision) library.  Following types of files are supported in OpenCV library: Windows bitmaps - *.bmp, *.dibJPEG files - *.jpeg, *.jpgPortable Network Graphics - *.png WebP - *.webp Sun ras
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences