Prev Tutorial:Making your own linear filters!
Nordvpn coupon 1 year. Next Tutorial:Sobel Derivatives
Create Negative or Invert Image using OpenCV Python This post will be helpful in learning OpenCV using Python programming. Here I will show how to implement OpenCV functions and apply them in various aspects using some great examples. Step 1: Download/clone both the main openCV files (opencvmaster) and the Additional Modules (opencvcontrib) from. Step 2: In the Cmake GUI, “configure” then “generate” the new build files in a new “build” folder you have created Open. Step 3: In your terminal, navigate to the ‘build’ folder. OpenCV-Python is a library of Python bindings designed to solve computer vision problems. Cv2.copyMakeBorder method is used to create a border around the image like a photo frame. Syntax: cv2.copyMakeBorder (src, top, bottom, left, right, borderType, value) Parameters: src: It is the source image. Top: It is the border width in number of pixels in top direction.
![Make Make](/uploads/1/3/7/3/137362598/680655672.jpg)
Goal
In this tutorial you will learn how to:
OpenCV, as a BSD-licensed software, makes it simple for companies to use and change the code. There are some predefined packages and libraries that make our life simple and OpenCV is one of them. Gary Bradsky invented OpenCV in 1999 and soon the first release came in 2000. We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.
- Use the OpenCV function copyMakeBorder() to set the borders (extra padding to your image).
Theory
- Note
- The explanation below belongs to the book Learning OpenCV by Bradski and Kaehler.
- In our previous tutorial we learned to use convolution to operate on images. One problem that naturally arises is how to handle the boundaries. How can we convolve them if the evaluated points are at the edge of the image?
- What most of OpenCV functions do is to copy a given image onto another slightly larger image and then automatically pads the boundary (by any of the methods explained in the sample code just below). This way, the convolution can be performed over the needed pixels without problems (the extra padding is cut after the operation is done).
- In this tutorial, we will briefly explore two ways of defining the extra padding (border) for an image: Ticktick siri.
- BORDER_CONSTANT: Pad the image with a constant value (i.e. black or (0)
- BORDER_REPLICATE: The row or column at the very edge of the original is replicated to the extra border.
This will be seen more clearly in the Code section.
- What does this program do?
- Load an image
- Let the user choose what kind of padding use in the input image. There are two options:
- Constant value border: Applies a padding of a constant value for the whole border. This value will be updated randomly each 0.5 seconds.
- Replicated border: The border will be replicated from the pixel values at the edges of the original image.
The user chooses either option by pressing 'c' (constant) or 'r' (replicate) - The program finishes when the user presses 'ESC'
Code
The tutorial code's is shown lines below.
You can also download it from here
#include 'opencv2/imgproc.hpp'
#include 'opencv2/highgui.hpp'
using namespace cv;
// Declare the variables
int top, bottom, left, right;
constchar* window_name = 'copyMakeBorder Demo';
{
constchar* imageName = argc >=2 ? argv[1] : 'lena.jpg';
// Loads an image
src = imread( samples::findFile( imageName ), IMREAD_COLOR ); // Load an image
// Check if image is loaded fine
printf(' Error opening imagen');
printf(' Program Arguments: [image_name -- default lena.jpg] n');
}
// Brief how-to for this program
printf( 't -------------------- n' );
printf( ' ** Press 'c' to set the border to a random constant value n');
printf( ' ** Press 'r' to set the border to be replicated n');
printf( ' ** Press 'ESC' to exit the program n');
namedWindow( window_name, WINDOW_AUTOSIZE );
// Initialize arguments for the filter
left = (int) (0.05*src.cols); right = left;
for(;;)
Scalar value( rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255) );
copyMakeBorder( src, dst, top, bottom, left, right, borderType, value );
imshow( window_name, dst );
char c = (char)waitKey(500);
{ break; }
{ borderType = BORDER_CONSTANT; }
{ borderType = BORDER_REPLICATE; }
}
You can also download it from here
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import java.util.Random;
class CopyMakeBorderRun {
publicvoid run(String[] args) {
// Declare the variables
int top, bottom, left, right;
String window_name = 'copyMakeBorder Demo';
String imageName = ((args.length > 0) ? args[0] : './data/lena.jpg');
// Load an image
src = Imgcodecs.imread(imageName, Imgcodecs.IMREAD_COLOR);
// Check if image is loaded fine
System.out.println('Error opening image!');
System.out.println('Program Arguments: [image_name -- default ./data/lena.jpg] n');
}
// Brief how-to for this program
't copyMakeBorder Demo: n' +
' ** Press 'c' to set the border to a random constant value n' +
' ** Press 'r' to set the border to be replicated n' +
HighGui.namedWindow( window_name, HighGui.WINDOW_AUTOSIZE );
// Initialize arguments for the filter
left = (int) (0.05*src.cols()); right = left;
while( true ) {
Scalar value = newScalar( rng.nextInt(256),
Core.copyMakeBorder( src, dst, top, bottom, left, right, borderType, value);
c = Character.toLowerCase(c);
if( c 27 )
elseif( c 'c' )
elseif( c 'r' )
}
System.exit(0);
}
publicclass CopyMakeBorder {
// Load the native library.
new CopyMakeBorderRun().run(args);
}
You can also download it from here
@file copy_make_border.py
@brief Sample code that shows the functionality of copyMakeBorder
import sys
import cv2 as cv
window_name = 'copyMakeBorder Demo'
imageName = argv[0] if len(argv) > 0 else'lena.jpg'
# Loads an image
src = cv.imread(cv.samples.findFile(imageName), cv.IMREAD_COLOR)
# Check if image is loaded fine
print ('Error opening image!')
print ('Usage: copy_make_border.py [image_name -- default lena.jpg] n')
't copyMakeBorder Demo: n'
' ** Press 'c' to set the border to a random constant value n'
' ** Press 'r' to set the border to be replicated n'
bottom = top
left = int(0.05 * src.shape[1]) # shape[1] = cols
value = [randint(0, 255), randint(0, 255), randint(0, 255)]
dst = cv.copyMakeBorder(src, top, bottom, left, right, borderType, None, value)
cv.imshow(window_name, dst)
c = cv.waitKey(500)
if c 27:
elif c 99: # 99 = ord('c')
elif c 114: # 114 = ord('r')
if __name__ '__main__':
Explanation
Declare the variables
Ticktick notion movie. First we declare the variables we are going to use:
C++
Mat src, dst;
int borderType = BORDER_CONSTANT;
RNG rng(12345);
Mat src, dst = new Mat();
int borderType = Core.BORDER_CONSTANT;
Random rng;
# First we declare the variables we are going to use
window_name = 'copyMakeBorder Demo'
Especial attention deserves the variable rng which is a random number generator. We use it to generate the random border color, as we will see soon.
Load an image
As usual we load our source image src:
constchar* imageName = argc >=2 ? argv[1] : 'lena.jpg';
// Loads an image
src = imread( samples::findFile( imageName ), IMREAD_COLOR ); // Load an image
// Check if image is loaded fine
printf(' Error opening imagen');
printf(' Program Arguments: [image_name -- default lena.jpg] n');
}
String imageName = ((args.length > 0) ? args[0] : './data/lena.jpg');
// Load an image
src = Imgcodecs.imread(imageName, Imgcodecs.IMREAD_COLOR);
// Check if image is loaded fine
System.out.println('Error opening image!');
System.out.println('Program Arguments: [image_name -- default ./data/lena.jpg] n');
}
imageName = argv[0] if len(argv) > 0 else'lena.jpg'
# Loads an image
src = cv.imread(cv.samples.findFile(imageName), cv.IMREAD_COLOR)
# Check if image is loaded fine
print ('Error opening image!')
print ('Usage: copy_make_border.py [image_name -- default lena.jpg] n')
Create a window
After giving a short intro of how to use the program, we create a window:
C++
Java
HighGui.namedWindow( window_name, HighGui.WINDOW_AUTOSIZE );
Initialize arguments
Now we initialize the argument that defines the size of the borders (top, bottom, left and right). We give them a value of 5% the size of src.
C++
top = (int) (0.05*src.rows); bottom = top;
Java
top = (int) (0.05*src.rows()); bottom = top;
Python
Opencv Make
top = int(0.05 * src.shape[0]) # shape[0] = rows
left = int(0.05 * src.shape[1]) # shape[1] = cols
Loop
The program runs in an infinite loop while the key ESC isn't pressed. If the user presses 'c' or 'r', the borderType variable takes the value of BORDER_CONSTANT or BORDER_REPLICATE respectively:
C++
if( c 27 )
elseif( c 'c' )
elseif( c 'r' )
Java
c = Character.toLowerCase(c);
if( c 27 )
elseif( c 'c' )
![Continuous Continuous](/uploads/1/3/7/3/137362598/377843722.jpg)
elseif( c 'r' )
Python
break
borderType = cv.BORDER_CONSTANT
borderType = cv.BORDER_REPLICATE
Random color
In each iteration (after 0.5 seconds), the random border color (value) is updated..
Scalar value( rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255) );
Scalar value = newScalar( rng.nextInt(256),
Python
value = [randint(0, 255), randint(0, 255), randint(0, 255)]
This value is a set of three numbers picked randomly in the range ([0,255]).
Form a border around the image
Finally, we call the function copyMakeBorder() to apply the respective padding:
copyMakeBorder( src, dst, top, bottom, left, right, borderType, value );
Core.copyMakeBorder( src, dst, top, bottom, left, right, borderType, value);
dst = cv.copyMakeBorder(src, top, bottom, left, right, borderType, None, value)
Opencv Make Image
- The arguments are:
- src: Source image
- dst: Destination image
- top, bottom, left, right: Length in pixels of the borders at each side of the image. We define them as being 5% of the original size of the image.
- borderType: Define what type of border is applied. It can be constant or replicate for this example.
- value: If borderType is BORDER_CONSTANT, this is the value used to fill the border pixels.
Display the results
We display our output image in the image created previously
Java
Python
Results
- After compiling the code above, you can execute it giving as argument the path of an image. The result should be:
- By default, it begins with the border set to BORDER_CONSTANT. Hence, a succession of random colored borders will be shown.
- If you press 'r', the border will become a replica of the edge pixels.
- If you press 'c', the random colored borders will appear again
- If you press 'ESC' the program will exit.
Below some screenshot showing how the border changes color and how the BORDER_REPLICATE option looks: