Showing posts with label Miscellaneous. Show all posts
Showing posts with label Miscellaneous. Show all posts

Crop elliptical region from image

We know that we can represent image as a matrix, and matrix can not be elliptical. So when you want to crop a elliptical area from an image, then you have to extract the elliptical region and remove rest of the information outside the ellipse. This can be done by AND operation of the image with an elliptical mask.

Steps:
  1. Read the image and convert to gray scale.
  2. Create the elliptical mask. ( use Negative argument to fill the ellipse)
    ellipse( im2, Point( 120, 130 ), Size( 50.0, 60.0 ), 0, 0, 360, Scalar( 255, 255, 255), -1, 8 );
  3. Use AND operation.
  4. Show the result.

Functions:

Example:

-------------
#include <opencv2/highgui/highgui.hpp>
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include<conio.h>


using namespace cv;
using namespace std;

int main()
{
    Mat im1 = imread("Lena.jpg");
    if (im1.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
 cvtColor(im1, im1, CV_BGR2GRAY);
    imshow("im1", im1);  // Origina image
 
 Mat im2(im1.rows, im1.cols, CV_8UC1, Scalar(0,0,0));
 ellipse( im2, Point( 120, 130 ), Size( 50.0, 60.0 ), 0, 0, 360, Scalar( 255, 255, 255), -1, 8 );
 imshow("im2",im2);  // mask
 
 Mat res;
 bitwise_and(im1,im2,res);     
 imshow("AND",res);  // resultant image

    waitKey(0);
 return 0;
}
-------------
Result:

Perspective Transform

Mat getPerspectiveTransform(InputArray src, InputArray dst)
- Calculates a perspective transform from four pairs of the corresponding points.

void warpPerspective(InputArray src, OutputArray dst, InputArray M, Size dsize, int flags=INTER_LINEAR, int borderMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar())
- Applies a perspective transformation to an image.
Parameters:
  • src – input image.
  • dst – output image that has the size dsize and the same type as src .
  • M3\times 3 transformation matrix.
  • dsize – size of the output image.
  • flags – combination of interpolation methods (INTER_LINEAR or INTER_NEAREST) and the optional flag WARP_INVERSE_MAP, that sets M as the inverse transformation ( \texttt{dst}\rightarrow\texttt{src} ).
  • borderMode – pixel extrapolation method (BORDER_CONSTANT or BORDER_REPLICATE).
  • borderValue – value used in case of a constant border; by default, it equals 0.

Example:

------------
#include<opencv2/opencv.hpp>

using namespace cv;

int main( )
{
    // Input Quadilateral or Image plane coordinates
    Point2f inputQuad[4]; 
    // Output Quadilateral or World plane coordinates
    Point2f outputQuad[4];
        
    // Lambda Matrix
    Mat lambda( 2, 4, CV_32FC1 );
    //Input and Output Image;
    Mat input, output;
    
    //Load the image
    input = imread( "lena.jpg", 1 );
    // Set the lambda matrix the same type and size as input
    lambda = Mat::zeros( input.rows, input.cols, input.type() );

    // The 4 points that select quadilateral on the input , from top-left in clockwise order
    // These four pts are the sides of the rect box used as input 
    inputQuad[0] = Point2f( -30,-60 );
    inputQuad[1] = Point2f( input.cols+50,-50);
    inputQuad[2] = Point2f( input.cols+100,input.rows+50);
    inputQuad[3] = Point2f( -50,input.rows+50  );  
    // The 4 points where the mapping is to be done , from top-left in clockwise order
    outputQuad[0] = Point2f( 0,0 );
    outputQuad[1] = Point2f( input.cols-1,0);
    outputQuad[2] = Point2f( input.cols-1,input.rows-1);
    outputQuad[3] = Point2f( 0,input.rows-1  );

    // Get the Perspective Transform Matrix i.e. lambda 
    lambda = getPerspectiveTransform( inputQuad, outputQuad );
    // Apply the Perspective Transform just found to the src image
    warpPerspective(input,output,lambda,output.size() );

    //Display input and output
    imshow("Input",input);
    imshow("Output",output);

    waitKey(0);
    return 0;
}
------------

Result:


Random number generator (Drawing colorful random lines)

class RNG - Random number generator.


RNG::next - Returns the next random number.
RNG::operator T - Returns the next random number of the specified type.
RNG::operator uchar()
RNG::operator ushort()
RNG::operator int()
RNG::operator unsigned int()
RNG::operator float()
RNG::operator double()
RNG::uniform - Returns the next random number sampled from the uniform distribution.
float RNG::uniform(float a, float b)
double RNG::uniform(double a, double b)
RNG::gaussian - Returns the next random number sampled from the Gaussian distribution.
double RNG::gaussian(double sigma)

RNG::fill - Fills arrays with random numbers.
void RNG::fill(InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange=false )


Example:
------------
RNG rng;

// always produces 0
double a = rng.uniform(0, 1);

// produces double from [0, 1)
double a1 = rng.uniform((double)0, (double)1);

// produces float from [0, 1)
double b = rng.uniform(0.f, 1.f);

// produces double from [0, 1)
double c = rng.uniform(0., 1.);

// may cause compiler error because of ambiguity:
//  RNG::uniform(0, (int)0.999999)? or RNG::uniform((double)0, 0.99999)?
double d = rng.uniform(0, 0.999999);
------------

The code provided below is slight modification of code given in OpenCV documentation.

Example 1: ( Drawing Colorful Random Lines )

-------------
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace cv;
using namespace std;

void Drawing_Random_Lines( Mat image, char* window_name, RNG rng, int NumOfLines, int windowHeight, int windowWidth );
static Scalar randomColor( RNG& rng );

int main( )
{    
    int windowHeight = 480, windowWidth=640;
    Mat image = Mat::zeros( windowHeight, windowWidth, CV_8UC3 );
    namedWindow( "Source", CV_WINDOW_AUTOSIZE );
    int n=1;
    while(1)
    {
    RNG rng(n);
    Drawing_Random_Lines(image, "Source", rng, 5, windowHeight, windowWidth);    
    imshow( "Source", image );
    waitKey(100);
    n++;
    }

    return(0);
}

void Drawing_Random_Lines( Mat image, char* window_name, RNG rng, int NumOfLines, int windowHeight, int windowWidth )
{
    int lineType = 8;
    Point pt1, pt2;

    for( int i = 0; i < NumOfLines; i++ )
    {
        pt1.x = rng.uniform( 0, windowWidth );
        pt1.y = rng.uniform( 0, windowHeight );
        pt2.x = rng.uniform( 0, windowWidth );
        pt2.y = rng.uniform( 0, windowHeight );

        line( image, pt1, pt2, randomColor(rng), rng.uniform(1, 10), 8 );
        imshow( window_name, image );
    }
}

static Scalar randomColor( RNG& rng )
{
    int icolor = (unsigned) rng;
    return Scalar( icolor&255, (icolor>>8)&255, (icolor>>16)&255 );
}
-------------

Example 2: ( Drawing Colorful Random Lines )

-------------
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace cv;
using namespace std;

void Drawing_Random_Lines( Mat image, char* window_name, RNG rng, int NumOfLines, int windowHeight, int windowWidth );
static Scalar randomColor( RNG& rng );

int main( )
{   
    int windowHeight = 480, windowWidth=640;
    Mat image = Mat::zeros( windowHeight, windowWidth, CV_8UC3 );
    namedWindow( "Source", CV_WINDOW_AUTOSIZE );
    int n=1;
    while(1)
    {
    RNG rng(n);
    Drawing_Random_Lines(image, "Source", rng, n, windowHeight, windowWidth);   
    imshow( "Source", image );
    waitKey(100);
    n++;
    }

    return(0);
}

void Drawing_Random_Lines( Mat image, char* window_name, RNG rng, int NumOfLines, int windowHeight, int windowWidth )
{
    int lineType = 8;
    Point pt1, pt2;

    for( int i = 0; i < NumOfLines; i++ )
    {
        pt1.x = rng.uniform( 0, windowWidth );
        pt1.y = rng.uniform( 0, windowHeight );
        pt2.x = rng.uniform( 0, windowWidth );
        pt2.y = rng.uniform( 0, windowHeight );

        line( image, pt1, pt2, randomColor(rng), rng.uniform(1, 10), 8 );
        imshow( window_name, image );
    }
}

static Scalar randomColor( RNG& rng )
{
    int icolor = (unsigned) rng;
    return Scalar( icolor&255, (icolor>>8)&255, (icolor>>16)&255 );
}

-------------

Result:


Draw circles at specific coordinates of a zero matrix

void randu (InputOutputArray dst, InputArray low, InputArray high)
Generates a single uniformly-distributed random number or an array of random numbers.

Parameters:
  • dst – output array of random numbers; the array must be pre-allocated.
  • low – inclusive lower boundary of the generated random numbers.
  • high – exclusive upper boundary of the generated random numbers.

This is a program to draw circles at specific positions of a zero matrix.

Steps:

  1. Get some random coordinates (matrix R with 15 points)
  2. Create a zero matrix
  3. Circle at each position
  4. Show the result

Functions:


Example:

--------------
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include<iostream>

using namespace cv;
using namespace std;

int main( int argc, char** argv )
{
    Mat R = Mat(15, 2, CV_32FC1);
    randu(R, Scalar(0), Scalar(255));
    cout << "R = " << endl << " " << R << endl << endl; 

    Mat Z = Mat::zeros(300,300, CV_8UC3);

    for(int i=0;i<15;i++)
    {
        circle( Z, Point( R.at<float>(i, 0), R.at<float>(i, 1) ), 5,  Scalar(255,0,255), 2, 8, 0 );
    }
    imshow("zeros2",Z);

    waitKey(0);
    return 0;
}
--------------