วันจันทร์ที่ 23 มกราคม พ.ศ. 2560

C++ opencv Save Video

#include <opencv\highgui.h>
#include <opencv\cv.h>
#include <iostream>

using namespace cv;
using namespace std;

string intToString(int number){


 std::stringstream ss;
 ss << number;
 return ss.str();
}

int main(int argc, char* argv[])
{
 bool recording = false;
 bool startNewRecording = false;
 int inc=0;
 bool firstRun = true;

 VideoCapture cap(0); // open the video camera no. 0
 VideoWriter oVideoWriter;//create videoWriter object, not initialized yet

 if (!cap.isOpened())  // if not success, exit program
 {
  cout << "ERROR: Cannot open the video file" << endl;
  return -1;
 }

 namedWindow("MyVideo",CV_WINDOW_AUTOSIZE); //create a window called "MyVideo"

 double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video
 double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video

 cout << "Frame Size = " << dWidth << "x" << dHeight << endl;

 //set framesize for use with videoWriter
 Size frameSize(static_cast<int>(dWidth), static_cast<int>(dHeight));


 while (1) {

  if(startNewRecording==true){

   
   oVideoWriter  = VideoWriter("D:/MyVideo"+intToString(inc)+".avi", CV_FOURCC('D', 'I', 'V', '3'), 20, frameSize, true); //initialize the VideoWriter object 
   //oVideoWriter  = VideoWriter("D:/MyVideo"+intToString(inc)+".avi", (int)cap.get(CV_CAP_PROP_FOURCC), 20, frameSize, true); //initialize the VideoWriter object 

   recording = true;
   startNewRecording = false;
   cout<<"New video file created D:/MyVideo"+intToString(inc)+".avi "<<endl;


   if ( !oVideoWriter.isOpened() ) //if not initialize the VideoWriter successfully, exit the program
   {
    cout << "ERROR: Failed to initialize video writing" << endl;
    getchar();
    return -1;
   }

  }


  Mat frame;

  bool bSuccess = cap.read(frame); // read a new frame from video

  if (!bSuccess) //if not success, break loop
  {
   cout << "ERROR: Cannot read a frame from video file" << endl;
   break;
  }

  //if we're in recording mode, write to file
  if(recording){

   oVideoWriter.write(frame);
   //show "REC" in top left corner in red
   //be sure to do this AFTER you write to the file so that "REC" doesn't show up
   //on the recorded video.
   putText(frame,"REC",Point(0,60),2,2,Scalar(0,0,255),2);


  }
  imshow("MyVideo", frame); //show the frame in "MyVideo" window


  switch(waitKey(10)){

  case 114:
   //'r' has been pressed.
   //toggle recording mode
   recording =!recording;

   if(firstRun == true){

    cout << "New Recording Started" << endl;
    oVideoWriter  = VideoWriter("D:/MyVideo0.avi", CV_FOURCC('D', 'I', 'V', '3'), 20, frameSize, true);

    if ( !oVideoWriter.isOpened() ) 
   {
    cout << "ERROR: Failed to initialize video writing" << endl;
    getchar();
    return -1;
   }
    firstRun = false;


   }
   else {if (!recording)cout << "Recording Stopped" << endl;

   else cout << "Recording Started" << endl;
   }
   break;

  case 110:
   //'n' has been pressed
   //start new video file
   startNewRecording = true;
   cout << "New Recording Started" << endl;
   //increment video file name
   inc+=1;
   break; 
  case 27:
   //'esc' has been pressed
   //exit program.
   cout << "Exit Program" << endl;
   return 0;



  }


 }

 return 0;

}
////////////////////////////////////////////////////////////////////////////////////////////

#include <opencv\highgui.h>
#include <opencv\cv.h>
#include <iostream>

using namespace cv;
using namespace std;

string intToString(int number){


 std::stringstream ss;
 ss << number;
 return ss.str();
}

int main(int argc, char* argv[])
{

 VideoCapture cap(0); // open the video camera no. 0

 cv::VideoWriter writer;


 if (!cap.isOpened())  // if not success, exit program
 {
  cout << "ERROR INITIALIZING VIDEO CAPTURE" << endl;
  return -1;
 }


 char* windowName = "Webcam Feed";
 namedWindow(windowName,CV_WINDOW_AUTOSIZE); //create a window to display our webcam feed

 //filename string

 string filename = "D:\myVideo.avi";

 //fourcc integer
 
 int fcc = CV_FOURCC('D','I','V','3');

 //frames per sec integer

 int fps = 10;

 //frame size

 cv::Size frameSize(cap.get(CV_CAP_PROP_FRAME_WIDTH),cap.get(CV_CAP_PROP_FRAME_HEIGHT));


 writer = VideoWriter(filename,fcc,fps,frameSize);

 if(!writer.isOpened()){

  cout<<"ERROR OPENING FILE FOR WRITE"<<endl;
  getchar();

  return -1;
 }

 Mat frame;

 while (1) {

  

  bool bSuccess = cap.read(frame); // read a new frame from camera feed

  if (!bSuccess) //test if frame successfully read
  {
   cout << "ERROR READING FRAME FROM CAMERA FEED" << endl;
   break;
  }

  writer.write(frame);
  
  imshow(windowName, frame); //show the frame in "MyVideo" window

  //listen for 10ms for a key to be pressed
  switch(waitKey(10)){

  case 27:
   //'esc' has been pressed (ASCII value for 'esc' is 27)
   //exit program.
   return 0;

  }


 }

 return 0;

}
////////////////////////////////////////////////////////////////////////////////////////////

วันพุธที่ 18 มกราคม พ.ศ. 2560

C++ opencv Load multi image in folder

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
#include <iostream>
#include <Windows.h>
using namespace std;
using namespace cv;
Point2f centerpoint(0, 0);
int j = 0;
Point2f computeIntersect(Vec4i a, Vec4i b) {
int x1 = a[0], y1 = a[1], x2 = a[2], y2 = a[3], x3 = b[0], y3 = b[1],
x4 = b[2], y4 = b[3];
if (float d = ((float)(x1 - x2) * (y3 - y4)) - ((y1 - y2) * (x3 - x4)))
{
Point2f pnt;
pnt.x = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 -
y3 * x4)) / d;
pnt.y = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 -
y3 * x4)) / d;
return pnt;
}
else
return Point2f(-1, -1);
}
void sortCorners(vector<Point2f>& corner_points, Point2f centerpoint)
{
vector<Point2f> top, bot;
for (int i = 0; i < corner_points.size(); i++)
{
if (corner_points[i].y < centerpoint.y)
top.push_back(corner_points[i]);
else
bot.push_back(corner_points[i]);
}
Point2f tl = top[0].x > top[1].x ? top[1] : top[0];
Point2f tr = top[0].x > top[1].x ? top[0] : top[1];
Point2f bl = bot[0].x > bot[1].x ? bot[1] : bot[0];
Point2f br = bot[0].x > bot[1].x ? bot[0] : bot[1];
corner_points.clear();
corner_points.push_back(tl);
corner_points.push_back(tr);
corner_points.push_back(br);
corner_points.push_back(bl);
}
int main()
{
/*
int dist = 1;
int theta = 180;
int threshold = 92;
int minLine = 30;
int maxLine = 20;
namedWindow("Perspectives", CV_WINDOW_AUTOSIZE);
createTrackbar("Distance Resolution","Perspectives", &dist, 5);
createTrackbar("Theta", "Perspectives", &theta, 180);
createTrackbar("threshold", "Perspectives", &threshold, 100);
createTrackbar("Min Line", "Perspectives", &minLine, 100);
createTrackbar("Max Line", "Perspectives", &maxLine, 100);
*/
vector<String>  filenames;
String  folder = "D:\\datas";
glob(folder, filenames);

while (j < filenames.size())
{
for (size_t i = 0; i < filenames.size(); i++)
{
Mat src = imread(filenames[i]);
if (!src.data)
return -1;
Mat dst = src.clone();

Mat bw;
cvtColor(src, bw, CV_BGR2GRAY);
Canny(bw, bw, 100, 100, 3);
vector<Vec4i> lines;
HoughLinesP(bw, lines, 1, CV_PI / 180, 92, 30, 20);
vector<Point2f> corner_points;
for (int i = 0; i < lines.size(); i++)
{
for (int j = i + 1; j < lines.size(); j++)
{
Point2f pnt = computeIntersect(lines[i], lines[j]);
if (pnt.x >= 0 && pnt.y >= 0)
corner_points.push_back(pnt);
}
}
vector<Point2f> approx;
approxPolyDP(Mat(corner_points), approx, arcLength(Mat(corner_points),
true) * 0.02, true);
//if (approx.size() != 4)
//{
// cout << "The object is not quadrilateral!" << endl;
//return -1;
//}
//Get center point
for (int i = 0; i < corner_points.size(); i++)
centerpoint += corner_points[i];
centerpoint *= (1. / corner_points.size());
sortCorners(corner_points, centerpoint);
//Draw lines
for (int i = 0; i < lines.size(); i++)
{
Vec4i v = lines[i];
line(dst, Point(v[0], v[1]), Point(v[2], v[3]), CV_RGB(0, 255, 0));
}
//Draw corner points
circle(dst, corner_points[0], 3, CV_RGB(255, 0, 0), 2);
circle(dst, corner_points[1], 3, CV_RGB(0, 255, 0), 2);
circle(dst, corner_points[2], 3, CV_RGB(0, 0, 255), 2);
circle(dst, corner_points[3], 3, CV_RGB(255, 255, 255), 2);
//Draw mass center points
circle(dst, centerpoint, 3, CV_RGB(255, 255, 0), 2);
//Calculate corresponding points for corner points
Mat quad = Mat::zeros(src.rows, src.cols, CV_8UC3);
vector<Point2f> quad_pnts;
quad_pnts.push_back(Point2f(0, 0));
quad_pnts.push_back(Point2f(quad.cols, 0));
quad_pnts.push_back(Point2f(quad.cols, quad.rows));
quad_pnts.push_back(Point2f(0, quad.rows));
// Draw corresponding points
circle(dst, quad_pnts[0], 3, CV_RGB(255, 0, 0), 2);
circle(dst, quad_pnts[1], 3, CV_RGB(0, 255, 0), 2);
circle(dst, quad_pnts[2], 3, CV_RGB(0, 0, 255), 2);
circle(dst, quad_pnts[3], 3, CV_RGB(255, 255, 255), 2);
Mat transmtx = getPerspectiveTransform(corner_points, quad_pnts);
warpPerspective(src, quad, transmtx, quad.size());
//Create windows and display results
//namedWindow("Original Image", CV_WINDOW_AUTOSIZE);
namedWindow("Selected Points", CV_WINDOW_AUTOSIZE);
namedWindow("Corrected Perspertive", CV_WINDOW_NORMAL);
//imshow("Original Image", src);
imshow("Selected Points", dst);
imshow("Corrected Perspertive", quad);

cout << filenames[i] << endl;

if (waitKey(30) == 27)
break;
Sleep(1000);
j++;
}
}
destroyAllWindows();
return 0; //End
}

C++ opencv convert string to char



char* DrawPic::ConvertString2Char(System::String^ str)
{
char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str);
return str2;
}


image = imread(drawpic.ConvertString2Char(open->FileName));

วันอังคารที่ 17 มกราคม พ.ศ. 2560

C++ opencv adjust perspective


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

using namespace std;
using namespace cv;
Point2f centerpoint(0, 0);
Point2f computeIntersect(Vec4i a, Vec4i b) {
int x1 = a[0], y1 = a[1], x2 = a[2], y2 = a[3], x3 = b[0], y3 = b[1],
x4 = b[2], y4 = b[3];
if (float d = ((float)(x1 - x2) * (y3 - y4)) - ((y1 - y2) * (x3 - x4)))
{
Point2f pnt;
pnt.x = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 -
y3 * x4)) / d;
pnt.y = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 -
y3 * x4)) / d;
return pnt;
}
else
return Point2f(-1, -1);
}
void sortCorners(vector<Point2f>& corner_points, Point2f centerpoint)
{
vector<Point2f> top, bot;
for (int i = 0; i < corner_points.size(); i++)
{
if (corner_points[i].y < centerpoint.y)
top.push_back(corner_points[i]);
else
bot.push_back(corner_points[i]);
}
Point2f tl = top[0].x > top[1].x ? top[1] : top[0];
Point2f tr = top[0].x > top[1].x ? top[0] : top[1];
Point2f bl = bot[0].x > bot[1].x ? bot[1] : bot[0];
Point2f br = bot[0].x > bot[1].x ? bot[0] : bot[1];
corner_points.clear();
corner_points.push_back(tl);
corner_points.push_back(tr);
corner_points.push_back(br);
corner_points.push_back(bl);
}
int main()
{
int dist = 1;
int theta = 180;
int threshold = 92;
int minLine = 30;
int maxLine = 20;
namedWindow("Perspectives", CV_WINDOW_AUTOSIZE);
createTrackbar("Distance Resolution","Perspectives", &dist, 5);
createTrackbar("Theta", "Perspectives", &theta, 180);
createTrackbar("threshold", "Perspectives", &threshold, 100);
createTrackbar("Min Line", "Perspectives", &minLine, 100);
createTrackbar("Max Line", "Perspectives", &maxLine, 100);

Mat src = imread("D:\\1213.jpg");
if (src.empty())
return -1;
Mat dst = src.clone();
while (1)
{
Mat bw;
cvtColor(src, bw, CV_BGR2GRAY);
Canny(bw, bw, 100, 100, 3);
vector<Vec4i> lines;
HoughLinesP(bw, lines, dist, CV_PI / theta, threshold, minLine, maxLine);
vector<Point2f> corner_points;
for (int i = 0; i < lines.size(); i++)
{
for (int j = i + 1; j < lines.size(); j++)
{
Point2f pnt = computeIntersect(lines[i], lines[j]);
if (pnt.x >= 0 && pnt.y >= 0)
corner_points.push_back(pnt);
}
}
vector<Point2f> approx;
approxPolyDP(Mat(corner_points), approx, arcLength(Mat(corner_points),
true) * 0.02, true);
//if (approx.size() != 4)
//{
// cout << "The object is not quadrilateral!" << endl;
//return -1;
//}
//Get center point
for (int i = 0; i < corner_points.size(); i++)
centerpoint += corner_points[i];
centerpoint *= (1. / corner_points.size());
sortCorners(corner_points, centerpoint);
//Draw lines
for (int i = 0; i < lines.size(); i++)
{
Vec4i v = lines[i];
line(dst, Point(v[0], v[1]), Point(v[2], v[3]), CV_RGB(0, 255, 0));
}
//Draw corner points
circle(dst, corner_points[0], 3, CV_RGB(255, 0, 0), 2);
circle(dst, corner_points[1], 3, CV_RGB(0, 255, 0), 2);
circle(dst, corner_points[2], 3, CV_RGB(0, 0, 255), 2);
circle(dst, corner_points[3], 3, CV_RGB(255, 255, 255), 2);
//Draw mass center points
circle(dst, centerpoint, 3, CV_RGB(255, 255, 0), 2);
//Calculate corresponding points for corner points
Mat quad = Mat::zeros(src.rows, src.cols, CV_8UC3);
vector<Point2f> quad_pnts;
quad_pnts.push_back(Point2f(0, 0));
quad_pnts.push_back(Point2f(quad.cols, 0));
quad_pnts.push_back(Point2f(quad.cols, quad.rows));
quad_pnts.push_back(Point2f(0, quad.rows));
// Draw corresponding points
circle(dst, quad_pnts[0], 3, CV_RGB(255, 0, 0), 2);
circle(dst, quad_pnts[1], 3, CV_RGB(0, 255, 0), 2);
circle(dst, quad_pnts[2], 3, CV_RGB(0, 0, 255), 2);
circle(dst, quad_pnts[3], 3, CV_RGB(255, 255, 255), 2);
Mat transmtx = getPerspectiveTransform(corner_points, quad_pnts);
warpPerspective(src, quad, transmtx, quad.size());
//Create windows and display results
//namedWindow("Original Image", CV_WINDOW_AUTOSIZE);
namedWindow("Selected Points", CV_WINDOW_AUTOSIZE);
namedWindow("Corrected Perspertive", CV_WINDOW_NORMAL);
//imshow("Original Image", src);
imshow("Selected Points", dst);
imshow("Corrected Perspertive", quad);
if (waitKey(30) == 27)
break;
}
destroyAllWindows();
return 0; //End
}


วันอาทิตย์ที่ 15 มกราคม พ.ศ. 2560

C++ opencv Line Table


#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <iostream>
using namespace std;
using namespace cv;

int main(int argc, char** args)
{
Mat src = imread("D:\\1213.jpg");
cvtColor(src, src, CV_BGR2GRAY);

Rect croppedRectangle = Rect(550, 400, 150, 255);
Mat croppedImage = src(croppedRectangle);

vector<vector<cv::Point>> contours;
vector<Vec4i> hierarchy;

Canny(src, src, 100, 200, 3);
//imshow("dda", src);

findContours(croppedImage, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

Mat drawing = Mat::zeros(croppedImage.size(), CV_8UC3);
char text[200] = " ";
//CvFont font = cvFont(2, 2);

for (int i = 0; i < contours.size(); i++)
{
drawContours(drawing, contours, i, CV_RGB(255, 0, 0), 1, 8, hierarchy, 0, Point());
cv::Rect brect = cv::boundingRect(contours[i]);
if (brect.area() < 1000)
continue;
sprintf(text, "S = %d", brect.area());
putText(drawing, text, cvPoint(brect.x+20, brect.y+20), 1, 1, CV_RGB(0, 255, 0));
rectangle(drawing, brect, CV_RGB(0, 0, 255), 2);
}
imshow("dd", drawing);
waitKey(0);
destroyAllWindows();
return 0;
}


วันพฤหัสบดีที่ 12 มกราคม พ.ศ. 2560

C++ opencv Crop Image


#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace cv;
using namespace std;

int main()
{
Mat image = imread("D:\\1213.jpg",1);
cout << image.size() << endl;
Rect croppedRectangle = Rect(7, 340, 695, 315);

Mat croppedImage = image(croppedRectangle);
imshow("output", croppedImage);
cout << croppedImage.size();
waitKey();
return 0;
}

C++ opencv pixel color



#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace cv;
using namespace std;

int main()
{
Mat image = imread("D:\\10.jpg",1);

for (int i = 0; i < image.rows; i++)
{
for (int j = 0; j > image.cols; j++)
{
if (image.at<Vec3b>(i, j)[0] == 255 && image.at<Vec3b>(i, j)[1] == 255 && image.at<Vec3b>(i, j)[2] == 255)
{
image.at<Vec3b>(i, j)[0] = 0;
image.at<Vec3b>(i, j)[1] = 0;
image.at<Vec3b>(i, j)[2] = 0;
}
}
}
imshow("output", image);
waitKey();
return 0;
}

============================

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace cv;
using namespace std;

int main()
{
Mat image = imread("D:\\1.jpg",1);

for (int i = 0; i < image.rows; i++)
{
for (int j = 0; j > image.cols; j++)
{
if (image.at<uchar>(i, j) >200)
{
image.at<uchar>(i, j) = 0;
}
}
}
imshow("output", image);
waitKey();
return 0;
}

C++ opencv Draw Rectsngle




C++ opencv Draw line





วันพฤหัสบดีที่ 5 มกราคม พ.ศ. 2560

C++ OPENCV


Get Pixel Image


========================================================================

#pragma once
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgcodecs/imgcodecs.hpp>
#include <msclr/marshal.h>
#include <iostream>

using namespace std;
using namespace cv;
namespace HistOpencv {

using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Runtime::InteropServices;

Mat src; // keep iamge
/// <summary>
/// Summary for MyForm
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{
public:
MyForm(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}

protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~MyForm()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^  button1;
protected:
private: System::Windows::Forms::Button^  button2;
private: System::Windows::Forms::PictureBox^  pictureBox1;
private: System::Windows::Forms::Label^  label1;
private: System::Windows::Forms::PictureBox^  pictureBox2;
private: System::Windows::Forms::PictureBox^  pictureBox3;
private: System::Windows::Forms::PictureBox^  pictureBox4;
private: System::Windows::Forms::PictureBox^  pictureBox5;
private: System::Windows::Forms::PictureBox^  pictureBox6;
private: System::Windows::Forms::PictureBox^  pictureBox7;
private: System::Windows::Forms::PictureBox^  pictureBox8;

private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^components;

#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
this->button1 = (gcnew System::Windows::Forms::Button());
this->button2 = (gcnew System::Windows::Forms::Button());
this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox());
this->label1 = (gcnew System::Windows::Forms::Label());
this->pictureBox2 = (gcnew System::Windows::Forms::PictureBox());
this->pictureBox3 = (gcnew System::Windows::Forms::PictureBox());
this->pictureBox4 = (gcnew System::Windows::Forms::PictureBox());
this->pictureBox5 = (gcnew System::Windows::Forms::PictureBox());
this->pictureBox6 = (gcnew System::Windows::Forms::PictureBox());
this->pictureBox7 = (gcnew System::Windows::Forms::PictureBox());
this->pictureBox8 = (gcnew System::Windows::Forms::PictureBox());
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->BeginInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox2))->BeginInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox3))->BeginInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox4))->BeginInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox5))->BeginInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox6))->BeginInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox7))->BeginInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox8))->BeginInit();
this->SuspendLayout();
// 
// button1
// 
this->button1->Location = System::Drawing::Point(12, 29);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(75, 23);
this->button1->TabIndex = 0;
this->button1->Text = L"Browse";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click);
// 
// button2
// 
this->button2->Location = System::Drawing::Point(93, 29);
this->button2->Name = L"button2";
this->button2->Size = System::Drawing::Size(75, 23);
this->button2->TabIndex = 1;
this->button2->Text = L"Process";
this->button2->UseVisualStyleBackColor = true;
this->button2->Click += gcnew System::EventHandler(this, &MyForm::button2_Click);
// 
// pictureBox1
// 
this->pictureBox1->Location = System::Drawing::Point(12, 78);
this->pictureBox1->Name = L"pictureBox1";
this->pictureBox1->Size = System::Drawing::Size(373, 300);
this->pictureBox1->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage;
this->pictureBox1->TabIndex = 2;
this->pictureBox1->TabStop = false;
// 
// label1
// 
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(12, 62);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(0, 13);
this->label1->TabIndex = 3;
// 
// pictureBox2
// 
this->pictureBox2->Location = System::Drawing::Point(391, 78);
this->pictureBox2->Name = L"pictureBox2";
this->pictureBox2->Size = System::Drawing::Size(382, 300);
this->pictureBox2->TabIndex = 4;
this->pictureBox2->TabStop = false;
// 
// pictureBox3
// 
this->pictureBox3->Location = System::Drawing::Point(779, 78);
this->pictureBox3->Name = L"pictureBox3";
this->pictureBox3->Size = System::Drawing::Size(400, 300);
this->pictureBox3->TabIndex = 5;
this->pictureBox3->TabStop = false;
// 
// pictureBox4
// 
this->pictureBox4->Location = System::Drawing::Point(391, 384);
this->pictureBox4->Name = L"pictureBox4";
this->pictureBox4->Size = System::Drawing::Size(382, 285);
this->pictureBox4->TabIndex = 6;
this->pictureBox4->TabStop = false;
// 
// pictureBox5
// 
this->pictureBox5->Location = System::Drawing::Point(779, 384);
this->pictureBox5->Name = L"pictureBox5";
this->pictureBox5->Size = System::Drawing::Size(400, 285);
this->pictureBox5->TabIndex = 7;
this->pictureBox5->TabStop = false;
// 
// pictureBox6
// 
this->pictureBox6->Location = System::Drawing::Point(15, 401);
this->pictureBox6->Name = L"pictureBox6";
this->pictureBox6->Size = System::Drawing::Size(370, 80);
this->pictureBox6->TabIndex = 8;
this->pictureBox6->TabStop = false;
// 
// pictureBox7
// 
this->pictureBox7->Location = System::Drawing::Point(15, 487);
this->pictureBox7->Name = L"pictureBox7";
this->pictureBox7->Size = System::Drawing::Size(370, 78);
this->pictureBox7->TabIndex = 9;
this->pictureBox7->TabStop = false;
// 
// pictureBox8
// 
this->pictureBox8->Location = System::Drawing::Point(15, 571);
this->pictureBox8->Name = L"pictureBox8";
this->pictureBox8->Size = System::Drawing::Size(370, 84);
this->pictureBox8->TabIndex = 10;
this->pictureBox8->TabStop = false;
// 
// MyForm
// 
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(1194, 681);
this->Controls->Add(this->pictureBox8);
this->Controls->Add(this->pictureBox7);
this->Controls->Add(this->pictureBox6);
this->Controls->Add(this->pictureBox5);
this->Controls->Add(this->pictureBox4);
this->Controls->Add(this->pictureBox3);
this->Controls->Add(this->pictureBox2);
this->Controls->Add(this->label1);
this->Controls->Add(this->pictureBox1);
this->Controls->Add(this->button2);
this->Controls->Add(this->button1);
this->KeyPreview = true;
this->Name = L"MyForm";
this->Text = L"MyForm";
this->KeyDown += gcnew System::Windows::Forms::KeyEventHandler(this, &MyForm::MyForm_KeyDown);
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->EndInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox2))->EndInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox3))->EndInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox4))->EndInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox5))->EndInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox6))->EndInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox7))->EndInit();
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox8))->EndInit();
this->ResumeLayout(false);
this->PerformLayout();

}
#pragma endregion
private: System::Void MyForm_KeyDown(System::Object^  sender, System::Windows::Forms::KeyEventArgs^  e)
{
if (e->KeyCode == Keys::Escape)
{
if (MessageBox::Show("Do you want to exit program", "HistOPENCV", MessageBoxButtons::OKCancel, MessageBoxIcon::Warning) == System::Windows::Forms::DialogResult::OK)
{
Application::Exit();
}
}
}
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)
{
OpenFileDialog^ open = gcnew OpenFileDialog();
open->Filter = "Image(*.jpg;*.bmp;*.png)|*.jpg;*.bmp;*.png";
if (open->ShowDialog() == System::Windows::Forms::DialogResult::Cancel)
{
return;
}
Bitmap^ bmpSrc = gcnew Bitmap(open->FileName);
pictureBox1->Image = bmpSrc;
pictureBox1->Refresh();

//Load Image into source variable and show as opencv method
src = imread(ConvertString2Char(open->FileName));
label1->Text = open->FileName->ToString();


}
private: char* ConvertString2Char(System::String^ str)
{
char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str);
return str2;
}

private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e)
{
Mat gray, red, blue, green, rorate, binary, adaptivebinary, resizing;

resizing = ToResize(src);
gray = ToGray(resizing);
DrawCVImage(pictureBox2, gray);

binary = ToBinary(gray);
DrawCVImage(pictureBox3, binary);

adaptivebinary = ToAdaptiveBinary(gray);
DrawCVImage(pictureBox4, adaptivebinary);

rorate = ToRorate(resizing, 45, 1);
DrawCVImage(pictureBox5, rorate);

red = ToHistogram(resizing)[0];
green = ToHistogram(resizing)[1];
blue = ToHistogram(resizing)[2];
DrawCVImage(pictureBox6, red);
DrawCVImage(pictureBox7, green);
DrawCVImage(pictureBox8, blue);
}
private: Mat ToResize(Mat src)
{
Mat dst;
resize(src, dst, cv::Size(320, 240), 0, 0, 1);
return dst;
}
private: Mat ToGray(Mat src)
{
Mat dst;
cvtColor(src, dst, CV_RGB2GRAY);
return dst;
}
private: Mat ToBinary(Mat src)
{
Mat dst;
threshold(src, dst, 100, 255, CV_THRESH_BINARY);
return dst;
}
private: Mat ToAdaptiveBinary(Mat src)
{
Mat dst;
adaptiveThreshold(src, dst, 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY,35, 5);
return dst;
}
private: Mat ToRorate(Mat src,double angle,double scale)
{
Mat dst;
Point2f center(src.cols / 2, src.rows / 2);
Mat mat_rot = getRotationMatrix2D(center, angle, scale);
warpAffine(src, dst, mat_rot, src.size());
return dst;
}
private: vector<Mat> ToHistogram(Mat src)
{
vector<Mat> result;
vector<Mat> img_rgb;
Mat img_r, img_b, img_g;

int chart_w = 400;
int chart_h = 400;

int size_histogram = 255;
float range[] = { 0,255 };

const float* hist_range = { range };

split(src, img_rgb);
calcHist(&img_rgb[0], 1, 0, Mat(), img_b, 1, &size_histogram, &hist_range, true, false);
calcHist(&img_rgb[1], 1, 0, Mat(), img_g, 1, &size_histogram, &hist_range, true, false);
calcHist(&img_rgb[2], 1, 0, Mat(), img_r, 1, &size_histogram, &hist_range, true, false);

int bin = cvRound((double)chart_w / size_histogram);

//Then we draw histogram here

Mat disp_r(chart_w, chart_h, CV_8UC3, Scalar(255, 255, 255));
Mat disp_g = disp_r.clone();
Mat disp_b = disp_r.clone();

normalize(img_b, img_r, 0, disp_b.rows, NORM_MINMAX, -1, Mat());
normalize(img_g, img_g, 0, disp_b.rows, NORM_MINMAX, -1, Mat());
normalize(img_r, img_b, 0, disp_b.rows, NORM_MINMAX, -1, Mat());

for (int i = 1; i < 255; i++)
{
line(disp_r, cv::Point(bin*(i), chart_h), cv::Point(bin*(i), chart_h - cvRound(img_r.at<float>(i))), Scalar(0, 0, 255), 2, 8, 0);
line(disp_g, cv::Point(bin*(i), chart_h), cv::Point(bin*(i), chart_h - cvRound(img_g.at<float>(i))), Scalar(0, 255, 0), 2, 8, 0);
line(disp_b, cv::Point(bin*(i), chart_h), cv::Point(bin*(i), chart_h - cvRound(img_b.at<float>(i))), Scalar(255, 0, 0), 2, 8, 0);
}

//push all 3 colors to the result variable
result.push_back(disp_r);
result.push_back(disp_g);
result.push_back(disp_b);

return result;
}
private: void DrawCVImage(System::Windows::Forms::Control^ control, cv::Mat& colorImage)
{
System::Drawing::Graphics^ graphics = control->CreateGraphics();
System::IntPtr ptr(colorImage.ptr());
System::Drawing::Bitmap^ b;
switch (colorImage.type())
{
case CV_8UC3: // non-grayscale images are correctly displayed here
b = gcnew System::Drawing::Bitmap(colorImage.cols, colorImage.rows, colorImage.step, System::Drawing::Imaging::PixelFormat::Format24bppRgb, ptr);
break;
case CV_8UC1: // grayscale images are incorrectly displayed here 
b = gcnew System::Drawing::Bitmap(colorImage.cols, colorImage.rows, colorImage.step,System::Drawing::Imaging::PixelFormat::Format8bppIndexed, ptr);
break;
default:
break;
}
System::Drawing::RectangleF rect(0, 0, (float)control->Width, (float)control->Height);
graphics->DrawImage(b, rect);
}
};
}

Function  ออกจากโปรแกรม