Monday, June 27, 2016

URI Online Judge Solution : 1006 Average 2 (Beginner Problem)


URI Online Judge | 1006

Average 2

Adapted by Neilor Tonin, URI  Brazil
Timelimit: 1
Read three values (variables A, B and C), which are the three student's grades. Then, calculate the average, considering that grade A has weight 2, grade B has weight 3 and the grade C has weight 5. Consider that each grade can go from 0 to 10.0, always with one decimal place.

Input

The input file contains 3 values of floating points with one digit after the decimal point.

Output

Print MEDIA(average in Portuguese) according to the following example, with a blank space before and after the equal signal.
Input SamplesOutput Samples
5.0
6.0
7.0
MEDIA = 6.3
5.0
10.0
10.0
MEDIA = 9.0
10.0
10.0
5.0
MEDIA = 7.5

Solution

#include<stdio.h>


int main()
{
 float A, B, C,MEDIA;
 scanf("%f %f %f", &A, &B, &C);

 MEDIA = ((A * 2) + (B * 3) + (C * 5)) / 10;
 printf("MEDIA = %.1f\n", MEDIA);
 return 0;
}

URI Online Judge Solution : 1005 Average 1 (Beginner Problem)


URI Online Judge | 1005

Average 1

Adapted by Neilor Tonin, URI  Brazil
Timelimit: 1
Read two floating points' values of double precision A and B, corresponding to two student's grades. After this, calculate the student's average, considering that grade A has weight 3.5 and B has weight 7.5. Each grade can be from zero to ten, always with one digit after the decimal point. Don’t forget to print the end of line after the result, otherwise you will receive “Presentation Error”. Don’t forget the space before and after the equal sign.

Input

The input file contains 2 floating points' values with one digit after the decimal point.

Output

Print MEDIA(average in Portuguese) according to the following example, with 5 digits after the decimal point and with a blank space before and after the equal signal.
Input SamplesOutput Samples
5.0
7.1
MEDIA = 6.43182
0.0
7.1
MEDIA = 4.84091
10.0
10.0
MEDIA = 10.00000

Solution


#include<stdio.h>


int main()
{
 double A, B,MEDIA;

 scanf("%lf %lf", &A, &B);
 MEDIA = ((A*3.5) + (B*7.5)) / 11;
 printf("MEDIA = %.5lf\n", MEDIA);
 return 0;
}

URI Online Judge Solution : 1004 Simple Product (Beginner Problem)


URI Online Judge | 1004

Simple Product

Adapted by Neilor Tonin, URI  Brazil
Timelimit: 1
Read two integer values. After this, calculate the product between them and store the result in a variable named PROD. Print the result like the example below. Do not forget to print the end of line after the result, otherwise you will receive “Presentation Error”.

Input

The input file contains 2 integer numbers.

Output

Print PROD according to the following example, with a blank space before and after the equal signal.
Input SamplesOutput Samples
3
9
PROD = 27
-30
10
PROD = -300
0
9
PROD = 0
Solution

#include<stdio.h>


int main()
{
 int A, B, PROD;
 scanf("%d %d", &A, &B);
 PROD = A*B;
 printf("PROD = %d\n", PROD);
 return 0;
}

URI Online Judge Solution : 1003 Simple Sum (Beginner Problem)


URI Online Judge | 1003

Simple Sum

Adapted by Neilor Tonin, URI Brazil
Timelimit: 1
Read two integer values, in this case, the variables A and B. After this, calculate the sum between them and assign it to the variable SOMA. Write the value of this variable.

Input

The input file contains 2 integer numbers.

Output

Print the variable SOMA with all the capital letters, with a blank space before and after the equal signal followed by the corresponding value to the sum of A and B. Like all the problems, don't forget to print the end of line, otherwise you will receive "Presentation Error"

Input SamplesOutput Samples
30
10
SOMA = 40
-30
10
SOMA = -20
0
0
SOMA = 0

 Solution


#include<stdio.h>


int main()
{
 int A, B, SOMA;
 scanf("%d %d", &A, &B);
 SOMA = A + B;
 printf("SOMA = %d\n", SOMA);
 return 0;
}



URI Online Judge Solution : 1002 Area of a Circle (Beginner Problem)


URI Online Judge | 1002

Area of a Circle

Adapted by Neilor Tonin, URI Brazil
Timelimit: 1
The formula to calculate the area of a circumference is defined as A = π . R2. Considering to this problem that π = 3.14159:
Calculate the area using the formula given in the problem description.

Input

The input contains a value of floating point (double precision), that is the variable R.

Output

Present the message "A=" followed by the value of the variable, as in the example bellow, with four places after the decimal point. Use all double precision variables. Like all the problems, don't forget to print the end of line after the result, otherwise you will receive "Presentation Error".
Input SamplesOutput Samples
2.00A=12.5664
100.64A=31819.3103
150.00A=70685.7750

 Solution


#include<stdio.h>


int main()
{
 double R,A;
 scanf("%lf", &R);
 A = 3.14159*R*R;
 printf("A=%.4lf\n", A);
 return 0;
}

 

URI Online Judge Solution : 1001 Extremely Basic (Beginner Problem)


URI Online Judge | 1001

Extremely Basic

Adapted by Neilor Tonin, URI Brazil
Timelimit: 1
Read 2 integer values and store them in variables, named A and B and make the sum of these two variables, assigning its result to the variable X. Print X as shown below. Don't present any message beyond what is being specified and don't forget to print the end of line after the result, otherwise you will receive “Presentation Error”.

Input

The input file contain 2 integer values.

Output

Print the variable X according to the following example, with a blank space before and after the equal signal. 'X' is uppercase and you have to print a blank space before and after the '=' signal.

Input SamplesOutput Samples
10
9
X = 19
-10
4
X = -6
15
-7
X = 8
  
Solution:
 

#include<stdio.h>

int main()
{
 int A, B, X;
 scanf("%d %d", &A, &B);
 X = A + B;
 printf("X = %d\n", X);
 return 0;
}

Saturday, June 25, 2016

How to Crop Video from Webcam using OpenCV

How to Crop Video from Webcam using OpenCV
In this tutorial you will learn how to crop a video which is captured from webcam.

Code:

#include<opencv2/highgui/highgui.hpp>

using namespace cv;
using namespace std;

Point point1, point2;
int drag = 0;
cv::Rect rect;
cv:: Mat img,roiImg;
int select_flag = 0;


void mouseHandler(int event, int x, int y, int flags, void* param)
{
    if (event == CV_EVENT_LBUTTONDOWN && !drag)
    {
        /* left button clicked. ROI selection begins */
        select_flag=0;
        point1 = Point(x, y);
        drag = 1;
    }

    if (event == CV_EVENT_MOUSEMOVE && drag)
    {
        /* mouse dragged. ROI being selected */
        Mat img1 = img.clone();
        point2 = Point(x, y);
        rectangle(img1, point1, point2, CV_RGB(255, 0, 0), 3, 8, 0);
        imshow("image", img1);
    }

    if (event == CV_EVENT_LBUTTONUP && drag)
    {
        point2 = Point(x, y);
        rect = Rect(point1.x,point1.y,x-point1.x,y-point1.y);
        drag = 0;
        roiImg = img(rect);
    }

    if (event == CV_EVENT_LBUTTONUP)
    {
       /* ROI selected */
        select_flag = 1;
        drag = 0;
    }
}




int main()
{

    VideoCapture cap = VideoCapture(0); /* Start webcam */
    cap >> img;
    imshow("image", img);
    while(1)
    {
        cap >> img;
        cvSetMouseCallback("image", mouseHandler, NULL);
        if (select_flag == 1)
        {
            imshow("ROI", roiImg); /* show the image bounded by the box */
        }
        rectangle(img, rect, CV_RGB(255, 0, 0), 3, 8, 0);
        imshow("image", img);


        if (waitKey(1) == 27)
        {
            break;
        }
    }
    return 0;
}

Output:
How to crop video

Writing video to File using OpenCV

Writing video to file using Opencv
In this tutorial you will learn how to write video file using OpenCV

Code:

#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

int main()
{
	// 0 is the ID of the built-in laptop camera, change if you want to use other camera
	VideoCapture cap(0);
	//check if the file was opened properly
	if (!cap.isOpened())
	{
		cout << "Capture could not be opened succesfully" << endl;
		return -1;
	}
	// Get size of frames
	Size S = Size((int)cap.get(CV_CAP_PROP_FRAME_WIDTH), (int)cap.get(CV_CAP_PROP_FRAME_HEIGHT));
	// Make a video writer object and initialize it at 30 FPS
	VideoWriter put("c://test//output.mpg", CV_FOURCC('M', 'P', 'E', 'G'), 30, S);
	if (!put.isOpened())
	{
		cout << "File could not be created for writing. Check permissions" << endl;
		return -1;
	}
	namedWindow("Video");
	
		// Play the video in a loop till it ends
	while (char(waitKey(1)) != 'q' && cap.isOpened())
	{
		Mat frame;
		cap >> frame;
		// Check if the video is over
		if (frame.empty())
		{
			cout << "Video over" << endl;
			break;
		}
		imshow("Video", frame);
		put << frame;
	}
	return 0;
}

Output:

How to Use Trackbar in OpenCV

Trackbar Option in OpenCV
In this tutorial you will learn how to use trackbar in OpenCV.

Code:

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

using namespace std;
using namespace cv;
// Global variables


const int slider_max = 2;
int slider;
Mat img;
// Callback function for trackbar event

void on_trackbar(int pos, void *)
{
	Mat img_converted;
	if (pos == 1)
	{
		cvtColor(img, img_converted, CV_RGB2HSV);
	}
	else if (pos==2)
	{
		cvtColor(img, img_converted, CV_RGB2GRAY);
	}
	else
		img_converted = img;

	imshow("Trackbar app", img_converted);
}


int main()
{
	img = imread("c://test//image1.jpg");
	namedWindow("Trackbar app");
	imshow("Trackbar app", img);
	
	slider = 0;

	//create the trackbar GUI for user option
	createTrackbar("Color", "Trackbar app", &slider, slider_max, on_trackbar);

	while (char(waitKey(1)) != 'q') 
	{

	}
	return 0;
}

Output:
Track bar option in OpenCV

Blurring Image Using OpenCV

Blurring an image
In this tutorial you will learn how to blur an image using image processing.

Code:

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
Mat image, image_blurred;
int slider = 5;

void on_trackbar(int, void *) {

	slider = slider % 2 == 0 ? slider + 1 : slider;

	GaussianBlur(image, image_blurred, Size(slider, slider),0);
	
	imshow("Blurred image", image_blurred);

}

int main() {

	image = imread("c://test//baboon.jpg");

	namedWindow("Original image");
	namedWindow("Blurred image");
	imshow("Original image", image);
	GaussianBlur(image, image_blurred, Size(slider, slider), 0);

	imshow("Blurred image", image_blurred);
	createTrackbar("Kernel Size", "Blurred image", &slider, 41, on_trackbar);

	while (char(waitKey(1) != 'q')) {}
	return 0;
}
 
Output:
Blurring an Image


Erode and Dilate using OpenCV

Erode and Dilate of an image
In this tutorial you will learn how to erode and dilate an image and how to do it using image processing
Code: 

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;


Mat image, image_processed;

int choice_slider = 0, size_slider = 5, structElement = 0; // 0 - erode, 1 - dilate

void process() {

	int Stype;
	if (structElement == 0)
	{
		Stype = MORPH_RECT;  //structure element is Rectangular
	}
	else if (structElement == 1)
	{
		Stype = MORPH_CROSS; //structure element is Cross
	}
	else if (structElement == 2)
	{
		Stype = MORPH_ELLIPSE; //structure element is Ellipse

	}

	Mat st_elem = getStructuringElement(Stype, Size(size_slider, size_slider));

	if (choice_slider == 0) {
		erode(image, image_processed, st_elem);
	}
	else {
		dilate(image, image_processed, st_elem);
	}

	imshow("Processed image", image_processed);
}


void on_choice_slider(int, void *) {
	process();
}

void on_size_slider(int, void *) {
	
	size_slider = size_slider % 2 == 0 ? size_slider + 1 : size_slider;
	process();
}

int main() {

	image = imread("c://test//image3.jpg");
	namedWindow("Original image");
	namedWindow("Processed image");
	imshow("Original image", image);

	Mat st_elem = getStructuringElement(MORPH_RECT, Size(size_slider, size_slider));
	erode(image, image_processed, st_elem);
	imshow("Processed image", image_processed);


	createTrackbar("Element: \n 0: Rect \n 1: Cross \n 2: Ellipse", "Processed image", &structElement, 2, on_choice_slider);
	createTrackbar("Erode/Dilate", "Processed image", &choice_slider, 1, on_choice_slider);
	createTrackbar("Kernel Size", "Processed image", &size_slider, 21, on_size_slider);
		
	
	while (char(waitKey(1) != 'q')) {}

	
	return 0;
}

Output:





Image Zoom Out and Zoom In using OpenCV

Image Zoom Out and Zoom In
In this tutorial you will learn how to zoom out or zoom in an image using OpenCV 

Code:

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>


using namespace cv;
using namespace std;

/// Global variables
Mat src, dst, tmp;
char* window_name = "Workshop : Pyramids Demo";

int main(int argc, char** argv)
{
	/// General instructions
	cout << "Zoom In-Out demo"<<endl;	
	cout << " ------------------"<<endl;
	cout<<" * [u] -> Zoom in"<<endl;
	cout<<" * [d] -> Zoom out"<<endl;
	cout << " * [q] -> Close program" << endl;

	/// Test image - Make sure it s divisible by 2^{n}

	src = imread("c://test//image1.jpg");

	if (!src.data)
	{
		printf(" No data! -- Exiting the program \n");
		return -1;
	}

	tmp = src;
	dst = tmp;
	/// Create window
	namedWindow(window_name, CV_WINDOW_AUTOSIZE);
	imshow(window_name, dst);
	/// Loop

	while (char(waitKey(1) != 'q'))
	{
		int c;

		c = waitKey(1);
		
		if ((char)c == 'u')
		{
			pyrUp(tmp, dst, Size(tmp.cols * 2, tmp.rows * 2));
			cout << " ** Zoom In: Image x 2"<<endl;
		}
		else if ((char)c == 'd')
		{
			pyrDown(tmp, dst, Size(tmp.cols / 2, tmp.rows / 2));
			cout<<" ** Zoom Out: Image / 2"<<endl;
		}
		imshow(window_name, dst);
		tmp = dst;
	}
	return 0;
}

Output:
Screenshot of the original, zoom out and zoom in images

Brightness and Contrast Control Using OpenCV

Brightness and Contrast Controlling
In this tutorial we will learn how to change the brightness and contrast of an image using OpenCV.

Operation:
Code:


#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace std;
using namespace cv;


double alpha; /**< Simple contrast control */
int beta; /**< Simple brightness control */

int main()
{
	/// Read image given by user
	Mat image = imread("c://test//image1.jpg", CV_LOAD_IMAGE_COLOR);
	Mat new_image = Mat::zeros(image.size(), image.type());

	/// Initialize values
	cout << " Basic Linear Transforms " << endl;
	cout << " ------------------------- " << endl;
	cout << " * Enter the alpha value [1.0-3.0]: ";
	cin >> alpha;
	cout << " * Enter the beta value [0-100]: ";
	cin >> beta;

	/// Do the operation new_image(i,j) = alpha*image(i,j) + beta

	for (int y = 0; y < image.rows; y++)
	{
		for (int x = 0; x < image.cols; x++)
		{
			for (int c = 0; c < 3; c++)
			{
				new_image.at<Vec3b>(y, x)[c] = saturate_cast<uchar>(alpha*(image.at<Vec3b>(y, x)[c]) + beta);
			}
		}
	}
		/// Create Windows
		namedWindow(" Original Image", 1);
		namedWindow(" New Image", 1);
		/// Show stuff
		imshow(" Original Image", image);
		imshow(" New Image", new_image);
		/// Wait until user press some key
		waitKey();
		return 0;
	
}

Note:

Output:

Brightness and Contrast Control

Blending of Images using Opencv

Blending of two images
In this tutorial we will learn how to blend two images together.

Operation:

Code:


#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace std;
using namespace cv;


int main()
{
 double alpha = 0.5; double beta; double input;
 Mat src1, src2, dst;
 /// Ask the user enter alpha
   cout << " Simple Linear Blender " << endl;
   cout << " ----------------------- " <<endl;
   cout << " * Enter alpha [0-1]: ";
   cin >> input;
 /// We use the alpha provided by the user if it is between 0 and 1
 if (input >= 0.0 && input <= 1.0)
 {
  alpha = input;
 }
 /// Read image ( same size, same type )
 src1 = imread("c://test//blend1.jpg");
 src2 = imread("c://test//blend2.jpg");
 if (!src1.data) 
 {
  cout<<" Error loading src1";
  return -1; 
 }

 if (!src2.data) 
 {
  cout<<" Error loading src2 \n";
  return -1;
 }
 /// Create Windows

 namedWindow("Blend1",1);
 imshow("Blend1", src1);


 namedWindow("Blend2", 1);
 imshow("Blend2", src2);

 namedWindow("Linear Blend", 1);
 beta = (1.0 - alpha);
 addWeighted(src1, alpha, src2, beta, 0.0, dst);

 imshow("Linear Blend", dst);
 waitKey(0);
 return 0;
}

Output:

Blending of two images