Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // OpenCVApplication.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include "common.h"
- #include <random>
- void testOpenImage()
- {
- char fname[MAX_PATH];
- while(openFileDlg(fname))
- {
- Mat src;
- src = imread(fname);
- imshow("image",src);
- waitKey();
- }
- }
- void testOpenImagesFld()
- {
- char folderName[MAX_PATH];
- if (openFolderDlg(folderName)==0)
- return;
- char fname[MAX_PATH];
- FileGetter fg(folderName,"bmp");
- while(fg.getNextAbsFile(fname))
- {
- Mat src;
- src = imread(fname);
- imshow(fg.getFoundFileName(),src);
- if (waitKey()==27) //ESC pressed
- break;
- }
- }
- void testImageOpenAndSave()
- {
- Mat src, dst;
- src = imread("Images/Lena_24bits.bmp", CV_LOAD_IMAGE_COLOR); // Read the image
- if (!src.data) // Check for invalid input
- {
- printf("Could not open or find the image\n");
- return;
- }
- // Get the image resolution
- Size src_size = Size(src.cols, src.rows);
- // Display window
- const char* WIN_SRC = "Src"; //window for the source image
- namedWindow(WIN_SRC, CV_WINDOW_AUTOSIZE);
- cvMoveWindow(WIN_SRC, 0, 0);
- const char* WIN_DST = "Dst"; //window for the destination (processed) image
- namedWindow(WIN_DST, CV_WINDOW_AUTOSIZE);
- cvMoveWindow(WIN_DST, src_size.width + 10, 0);
- cvtColor(src, dst, CV_BGR2GRAY); //converts the source image to a grayscale one
- imwrite("Images/Lena_24bits_gray.bmp", dst); //writes the destination to file
- imshow(WIN_SRC, src);
- imshow(WIN_DST, dst);
- printf("Press any key to continue ...\n");
- waitKey(0);
- }
- void testNegativeImage()
- {
- char fname[MAX_PATH];
- while(openFileDlg(fname))
- {
- double t = (double)getTickCount(); // Get the current time [s]
- Mat src = imread(fname,CV_LOAD_IMAGE_GRAYSCALE);
- int height = src.rows;
- int width = src.cols;
- Mat dst = Mat(height,width,CV_8UC1);
- // Asa se acceseaaza pixelii individuali pt. o imagine cu 8 biti/pixel
- // Varianta ineficienta (lenta)
- for (int i=0; i<height; i++)
- {
- for (int j=0; j<width; j++)
- {
- uchar val = src.at<uchar>(i,j);
- uchar neg = 255 - val;
- dst.at<uchar>(i,j) = neg;
- }
- }
- // Get the current time again and compute the time difference [s]
- t = ((double)getTickCount() - t) / getTickFrequency();
- // Print (in the console window) the processing time in [ms]
- printf("Time = %.3f [ms]\n", t * 1000);
- imshow("input image",src);
- imshow("negative image",dst);
- waitKey();
- }
- }
- void testParcurgereSimplaDiblookStyle()
- {
- char fname[MAX_PATH];
- while (openFileDlg(fname))
- {
- Mat src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
- int height = src.rows;
- int width = src.cols;
- Mat dst = src.clone();
- double t = (double)getTickCount(); // Get the current time [s]
- // the fastest approach using the “diblook style”
- uchar *lpSrc = src.data;
- uchar *lpDst = dst.data;
- int w = (int) src.step; // no dword alignment is done !!!
- for (int i = 0; i<height; i++)
- for (int j = 0; j < width; j++) {
- uchar val = lpSrc[i*w + j];
- lpDst[i*w + j] = 255 - val;
- }
- // Get the current time again and compute the time difference [s]
- t = ((double)getTickCount() - t) / getTickFrequency();
- // Print (in the console window) the processing time in [ms]
- printf("Time = %.3f [ms]\n", t * 1000);
- imshow("input image",src);
- imshow("negative image",dst);
- waitKey();
- }
- }
- void testColor2Gray()
- {
- char fname[MAX_PATH];
- while(openFileDlg(fname))
- {
- Mat src = imread(fname);
- int height = src.rows;
- int width = src.cols;
- Mat dst = Mat(height,width,CV_8UC1);
- // Asa se acceseaaza pixelii individuali pt. o imagine RGB 24 biti/pixel
- // Varianta ineficienta (lenta)
- for (int i=0; i<height; i++)
- {
- for (int j=0; j<width; j++)
- {
- Vec3b v3 = src.at<Vec3b>(i,j);
- uchar b = v3[0];
- uchar g = v3[1];
- uchar r = v3[2];
- dst.at<uchar>(i,j) = (r+g+b)/3;
- }
- }
- imshow("input image",src);
- imshow("gray image",dst);
- waitKey();
- }
- }
- void testBGR2HSV()
- {
- char fname[MAX_PATH];
- while (openFileDlg(fname))
- {
- Mat src = imread(fname);
- int height = src.rows;
- int width = src.cols;
- // Componentele d eculoare ale modelului HSV
- Mat H = Mat(height, width, CV_8UC1);
- Mat S = Mat(height, width, CV_8UC1);
- Mat V = Mat(height, width, CV_8UC1);
- // definire pointeri la matricele (8 biti/pixeli) folosite la afisarea componentelor individuale H,S,V
- uchar* lpH = H.data;
- uchar* lpS = S.data;
- uchar* lpV = V.data;
- Mat hsvImg;
- cvtColor(src, hsvImg, CV_BGR2HSV);
- // definire pointer la matricea (24 biti/pixeli) a imaginii HSV
- uchar* hsvDataPtr = hsvImg.data;
- for (int i = 0; i<height; i++)
- {
- for (int j = 0; j<width; j++)
- {
- int hi = i*width * 3 + j * 3;
- int gi = i*width + j;
- lpH[gi] = hsvDataPtr[hi] * 510 / 360; // lpH = 0 .. 255
- lpS[gi] = hsvDataPtr[hi + 1]; // lpS = 0 .. 255
- lpV[gi] = hsvDataPtr[hi + 2]; // lpV = 0 .. 255
- }
- }
- imshow("input image", src);
- imshow("H", H);
- imshow("S", S);
- imshow("V", V);
- waitKey();
- }
- }
- void testResize()
- {
- char fname[MAX_PATH];
- while(openFileDlg(fname))
- {
- Mat src;
- src = imread(fname);
- Mat dst1,dst2;
- //without interpolation
- resizeImg(src,dst1,320,false);
- //with interpolation
- resizeImg(src,dst2,320,true);
- imshow("input image",src);
- imshow("resized image (without interpolation)",dst1);
- imshow("resized image (with interpolation)",dst2);
- waitKey();
- }
- }
- void testCanny()
- {
- char fname[MAX_PATH];
- while(openFileDlg(fname))
- {
- Mat src,dst,gauss;
- src = imread(fname,CV_LOAD_IMAGE_GRAYSCALE);
- double k = 0.4;
- int pH = 50;
- int pL = (int) k*pH;
- GaussianBlur(src, gauss, Size(5, 5), 0.8, 0.8);
- Canny(gauss,dst,pL,pH,3);
- imshow("input image",src);
- imshow("canny",dst);
- waitKey();
- }
- }
- void testVideoSequence()
- {
- VideoCapture cap("Videos/rubic.avi"); // off-line video from file
- //VideoCapture cap(0); // live video from web cam
- if (!cap.isOpened()) {
- printf("Cannot open video capture device.\n");
- waitKey(0);
- return;
- }
- Mat edges;
- Mat frame;
- char c;
- while (cap.read(frame))
- {
- Mat grayFrame;
- cvtColor(frame, grayFrame, CV_BGR2GRAY);
- Canny(grayFrame,edges,40,100,3);
- imshow("source", frame);
- imshow("gray", grayFrame);
- imshow("edges", edges);
- c = cvWaitKey(0); // waits a key press to advance to the next frame
- if (c == 27) {
- // press ESC to exit
- printf("ESC pressed - capture finished\n");
- break; //ESC pressed
- };
- }
- }
- void testSnap()
- {
- VideoCapture cap(0); // open the deafult camera (i.e. the built in web cam)
- if (!cap.isOpened()) // openenig the video device failed
- {
- printf("Cannot open video capture device.\n");
- return;
- }
- Mat frame;
- char numberStr[256];
- char fileName[256];
- // video resolution
- Size capS = Size((int)cap.get(CV_CAP_PROP_FRAME_WIDTH),
- (int)cap.get(CV_CAP_PROP_FRAME_HEIGHT));
- // Display window
- const char* WIN_SRC = "Src"; //window for the source frame
- namedWindow(WIN_SRC, CV_WINDOW_AUTOSIZE);
- cvMoveWindow(WIN_SRC, 0, 0);
- const char* WIN_DST = "Snapped"; //window for showing the snapped frame
- namedWindow(WIN_DST, CV_WINDOW_AUTOSIZE);
- cvMoveWindow(WIN_DST, capS.width + 10, 0);
- char c;
- int frameNum = -1;
- int frameCount = 0;
- for (;;)
- {
- cap >> frame; // get a new frame from camera
- if (frame.empty())
- {
- printf("End of the video file\n");
- break;
- }
- ++frameNum;
- imshow(WIN_SRC, frame);
- c = cvWaitKey(10); // waits a key press to advance to the next frame
- if (c == 27) {
- // press ESC to exit
- printf("ESC pressed - capture finished");
- break; //ESC pressed
- }
- if (c == 115){ //'s' pressed - snapp the image to a file
- frameCount++;
- fileName[0] = NULL;
- sprintf(numberStr, "%d", frameCount);
- strcat(fileName, "Images/A");
- strcat(fileName, numberStr);
- strcat(fileName, ".bmp");
- bool bSuccess = imwrite(fileName, frame);
- if (!bSuccess)
- {
- printf("Error writing the snapped image\n");
- }
- else
- imshow(WIN_DST, frame);
- }
- }
- }
- float computeElongationAxis(Mat_<Vec3b> src, Vec3b color, int iCenter, int jCenter)
- {
- int cols = src.cols;
- int rows = src.rows;
- int s1 = 0, s2 = 0;
- for (int i = 0; i < rows; i++)
- {
- for (int j = 0; j < cols; j++)
- {
- if (src(i, j) == color)
- {
- s1 = s1 + (i - iCenter)*(j - jCenter);
- s2 = s2 +(j - jCenter)*(j - jCenter) - (i - iCenter)*(i - iCenter);
- }
- }
- }
- s1 = s1*2;
- return atan2(s1, s2)/ 2.0f;
- }
- Point computeCenterOfMass(Mat_<Vec3b> src, Vec3b selectedColor, int Area ) {
- int cols = src.cols;
- int rows = src.rows;
- int iCenter = 0, jCenter = 0;
- for (int i = 0; i < rows; i++) {
- for (int j = 0; j < cols; j++) {
- if (src(i, j) == selectedColor) {
- iCenter = iCenter + i;
- jCenter = jCenter + j;
- }
- }
- }
- iCenter = iCenter / Area;
- jCenter = jCenter / Area;
- return Point(jCenter, iCenter);
- }
- int computeArea(Mat_<Vec3b> src, Vec3b selectedColor)
- {
- int Area = 0;
- for (int i = 0; i < src.rows; i++)
- {
- for (int j = 0; j < src.cols; j++)
- {
- if (src(i, j) == selectedColor)
- {
- Area++;
- }
- }
- }
- return Area;
- }
- void MyCallBackFunc(int event, int x, int y, int flags, void* param)
- {
- //More examples: http://opencvexamples.blogspot.com/2014/01/detect-mouse-clicks-and-moves-on-image.html
- Mat_<Vec3b>* src = (Mat_<Vec3b>*)param;
- Mat_<Vec3b> copy;
- Vec3b selectedColor;
- Point centerOfMass;
- Point Point1, Point2;
- float angleRad, angleDegree;
- if (event == CV_EVENT_LBUTTONDOWN)
- {
- copy = *src;
- printf("Pos(x,y): %d,%d Color(RGB): %d,%d,%d\n",
- x, y,
- (int)(*src).at<Vec3b>(y, x)[2],
- (int)(*src).at<Vec3b>(y, x)[1],
- (int)(*src).at<Vec3b>(y, x)[0]);
- selectedColor = (*src).at<Vec3b>(y, x);
- int Area = computeArea(*src, selectedColor);
- printf("%d\n", Area);
- centerOfMass = computeCenterOfMass(*src, selectedColor, Area);
- printf("%d , %d\n", centerOfMass.x, centerOfMass.y);
- circle(copy, centerOfMass, 5, Scalar(255, 0, 255), -1);
- imshow("Copy", copy);
- angleRad = computeElongationAxis(*src, selectedColor, centerOfMass.y, centerOfMass.x);
- angleDegree = angleRad * 180 / 3, 14;
- printf("%f\n", angleDegree);
- Point1.x = centerOfMass.x - 30;
- Point2.x = centerOfMass.x + 30;
- int y = 30 * tan(angleRad);
- Point1.y = centerOfMass.y - y;
- Point2.y = centerOfMass.y + y;
- line(copy, Point1, Point2, Scalar(0, 0, 0));
- }
- }
- void testMouseClick()
- {
- Mat src;
- // Read image from file
- char fname[MAX_PATH];
- while (openFileDlg(fname))
- {
- src = imread(fname);
- //Create a window
- namedWindow("My Window", 1);
- //set the callback function for any mouse event
- setMouseCallback("My Window", MyCallBackFunc, &src);
- //show the image
- imshow("My Window", src);
- // Wait until user press some key
- waitKey(0);
- }
- }
- /* Histogram display function - display a histogram using bars (simlilar to L3 / PI)
- Input:
- name - destination (output) window name
- hist - pointer to the vector containing the histogram values
- hist_cols - no. of bins (elements) in the histogram = histogram image width
- hist_height - height of the histogram image
- Call example:
- showHistogram ("MyHist", hist_dir, 255, 200);
- */
- void showHistogram(const std::string& name, int* hist, const int hist_cols, const int hist_height)
- {
- Mat imgHist(hist_height, hist_cols, CV_8UC3, CV_RGB(255, 255, 255)); // constructs a white image
- //computes histogram maximum
- int max_hist = 0;
- for (int i = 0; i<hist_cols; i++)
- if (hist[i] > max_hist)
- max_hist = hist[i];
- double scale = 1.0;
- scale = (double)hist_height / max_hist;
- int baseline = hist_height - 1;
- for (int x = 0; x < hist_cols; x++) {
- Point p1 = Point(x, baseline);
- Point p2 = Point(x, baseline - cvRound(hist[x] * scale));
- line(imgHist, p1, p2, CV_RGB(255, 0, 255)); // histogram bins colored in magenta
- }
- imshow(name, imgHist);
- }
- void copy_RGB()
- {
- char filename[MAX_PATH];
- openFileDlg(filename);
- Mat_<Vec3b> src;
- src = imread(filename); ///opencv returns BGR
- imshow("image", src);
- Mat_<uchar> r(src.rows,src.cols);
- Mat_<uchar> g(src.rows,src.cols);
- Mat_<uchar> b(src.rows,src.cols);
- for (int i = 0; i < src.rows; i++)
- {
- for (int j = 0; j < src.cols; j++)
- {
- b(i, j) = src(i, j)[0];
- g(i, j) = src(i, j)[1];
- r(i, j) = src(i, j)[2];
- }
- }
- imshow("blue", b);
- imshow("green", g);
- imshow("red", r);
- waitKey();
- }
- void convert_to_grayscale()
- {
- char filename[MAX_PATH];
- openFileDlg(filename);
- Mat_<Vec3b> src;
- src = imread(filename);
- imshow("image", src);
- Mat_<uchar> grayscale(src.rows,src.cols);
- for (int i = 0; i < src.rows; i++)
- {
- for (int j = 0; j < src.cols; j++)
- {
- grayscale(i, j) = (src(i, j)[0] + src(i, j)[1] + src(i, j)[2]) / 3;
- }
- }
- imshow("grayscale", grayscale);
- waitKey();
- }
- void convert_to_binary()
- {
- char filename[MAX_PATH];
- openFileDlg(filename);
- Mat_<uchar> src;
- src = imread(filename,0);
- int treshold;
- Mat_<uchar> binary(src.rows,src.cols);
- std::cout << "Treshold: ";
- std::cin >> treshold;
- std::cout << "\n";
- for (int i = 0; i < src.rows; i++)
- {
- for (int j = 0; j < src.cols; j++)
- {
- if (src(i, j) < treshold)
- {
- binary(i, j) = 0;
- }
- else
- {
- binary(i, j) = 255;
- }
- }
- }
- imshow("image", src);
- imshow("binary", binary);
- waitKey();
- }
- void compute_HSV()
- {
- char filename[MAX_PATH];
- openFileDlg(filename);
- Mat_<Vec3b> src;
- src = imread(filename);
- float r, g, b, m, M, C, V, H, S;
- Mat_<uchar> h(src.rows, src.cols);
- Mat_<uchar> s(src.rows, src.cols);
- Mat_<uchar> v(src.rows,src.cols);
- for (int i = 0; i < src.rows; i++)
- {
- for (int j = 0; j < src.cols; j++)
- {
- r = (float)src(i, j)[2] / 255;
- g = (float)src(i, j)[1] / 255;
- b = (float)src(i, j)[0] / 255;
- M = max(max(r, g), b);
- m = min(min(r, g), b);
- C = M - m;
- V = M;
- if (V != 0)
- {
- S = C / V;
- }
- else
- {
- S = 0;
- }
- if (C != 0)
- {
- if (M == r)
- {
- H = 60 * (g - b) / C;
- }
- if (M == g)
- {
- H = 120 + 60 * (b - r) / C;
- }
- if (M == b)
- {
- H = 240 + 60 * (r - g) / C;
- }
- }
- else
- {
- H = 0;
- }
- if (H < 0)
- {
- H = H + 360;
- }
- uchar H_norm = H * 255 / 360;
- uchar S_norm = S * 255;
- uchar V_norm = V * 255;
- h(i, j) = H_norm;
- s(i, j) = S_norm;
- v(i, j) = V_norm;
- }
- }
- imshow("image", src);
- imshow("h", h);
- imshow("s", s);
- imshow("v", v);
- waitKey();
- }
- int* compute_histogram(Mat_<uchar> src) {
- int * histogram = new int[256]();
- for (int i = 0; i < src.rows; i++) {
- for (int j = 0; j < src.cols; j++) {
- histogram[src(i, j)]++;
- }
- }
- return histogram;
- }
- void test_histogram() {
- char filename[MAX_PATH];
- int * histogram = new int[256]();
- openFileDlg(filename);
- Mat_<uchar> src;
- src = imread(filename, CV_LOAD_IMAGE_GRAYSCALE);
- imshow("image", src);
- histogram = compute_histogram(src);
- showHistogram("Histogram", histogram, 255, 255);
- waitKey();
- }
- float * compute_PDF(Mat_<uchar> src) {
- int * histogram = compute_histogram(src);
- float PDF[256];
- int M = src.rows * src.cols;
- for (int i = 0; i < 256; i++) {
- PDF[i] = histogram[i] / M;
- }
- return PDF;
- }
- void test_PDF() {
- char filename[MAX_PATH];
- openFileDlg(filename);
- Mat_<uchar> src;
- src = imread(filename, CV_LOAD_IMAGE_GRAYSCALE);
- imshow("image", src);
- compute_PDF(src);
- waitKey();
- }
- int * compute_bins_histogram(Mat_<uchar> src, int bins) {
- int * histogram = new int[bins]();
- float N = 256 / bins;
- for (int i = 0; i < src.rows; i++) {
- for (int j = 0; j < src.cols; j++) {
- histogram[(int)(src(i, j)/N)]++;
- }
- }
- return histogram;
- }
- void test_bins_histogram() {
- printf("Bins=");
- int bins;
- scanf("%d", &bins);
- char filename[MAX_PATH];
- int * histogram = new int[bins]();
- openFileDlg(filename);
- Mat_<uchar> src;
- src = imread(filename, CV_LOAD_IMAGE_GRAYSCALE);
- imshow("image", src);
- histogram = compute_bins_histogram(src,bins);
- showHistogram("Histogram", histogram, bins, 255);
- waitKey();
- }
- uchar getMaxima(std::vector<int> maximas, uchar pixel)
- {
- int minDif = 1000;
- int pos;
- int dif;
- for (int i = 0; i < maximas.size(); i++)
- {
- dif = std::abs(pixel - maximas[i]);
- if (dif < minDif)
- {
- minDif = dif;
- pos = maximas[i];
- }
- }
- return pos;
- }
- std::vector<int> computeMaxima(float* pdf)
- {
- int WH = 5;
- float TH = 0.0003;
- float avg = 0;
- bool maxima = true;
- std::vector<int> maximas;
- maximas.push_back(0);
- for (int k = WH; k < 255 - WH; k++)
- {
- maxima = true;
- avg = 0;
- for (int i = k - WH; i <= k + WH; i++)
- {
- if (pdf[k] < pdf[i])
- {
- maxima = false;
- }
- avg += pdf[i];
- }
- avg = avg / (2 * WH + 1);
- if ((pdf[k] > avg + TH) && maxima)
- {
- maximas.push_back(k);
- }
- if (maxima)
- {
- }
- }
- maximas.push_back(255);
- return maximas;
- }
- void multilevelThresholding(Mat_<uchar> src, float* pdf)
- {
- int WH = 5;
- float TH = 0.0003;
- float avg = 0;
- bool maxima = true;
- int size = src.cols * src.rows;
- Mat_<uchar> dest(src.rows, src.cols);
- std::vector<int> maximas;
- maximas = computeMaxima(pdf);
- uchar pixel;
- for (int i = 0; i < src.rows; i++)
- {
- for (int j = 0; j < src.cols; j++)
- {
- pixel = src(i, j);
- dest(i, j) = getMaxima(maximas, pixel);
- }
- }
- imshow("src", src);
- imshow("dest", dest);
- waitKey();
- }
- void testThresholding()
- {
- char fname[MAX_PATH];
- openFileDlg(fname);
- Mat_<uchar> src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
- int* hist = compute_histogram(src);
- showHistogram("hist", hist, 255, 255);
- float* pdf = compute_PDF(src);
- multilevelThresholding(src, pdf);
- delete[] pdf;
- delete[] hist;
- }
- Mat_<uchar> breadth_first_traversal(Mat_<uchar> src) {
- int di[8] = { -1, 0, 1, 0, -1, 1, 1, -1 };
- int dj[8] = { 0, -1, 0, 1, -1, -1, 1, 1 };
- int N;
- int label = 0;
- int height = src.rows;
- int width = src.cols;
- Mat_<uchar> labels = Mat_<uchar>::zeros(height, width);
- printf("Insert neighborhood type(4 or 8):");
- scanf("%d", &N);
- for (int i = 0; i < height; i++) {
- for (int j = 0; j < width; j++) {
- if (src(i, j) == 0 && labels(i, j) == 0){
- label++;
- printf("New label found\n");
- std::queue<Point> Q;
- labels(i, j) = label;
- Q.push(Point(i, j));
- while (!Q.empty()) {
- Point q = Q.front();
- Q.pop();
- for (int k = 0; k < N; k++) {
- Point neighbor(q.x+di[k],q.y+dj[k]);
- if(neighbor.x>=0 && neighbor.x < src.rows && neighbor.y >=0 && neighbor.y < src.cols){
- if (src(neighbor.x, neighbor.y) == 0 && labels(neighbor.x, neighbor.y) == 0) {
- labels(neighbor.x, neighbor.y) = label;
- Q.push(neighbor);
- }
- }
- }
- }
- }
- }
- }
- return labels;
- }
- Mat_<Vec3b> colorLabels(Mat_<uchar> labels) {
- std::default_random_engine gen;
- std::uniform_int_distribution<int> d(0, 255);
- Mat_<Vec3b> destination(labels.rows,labels.cols);
- uchar x = d(gen);
- std::vector<Vec3b> colors;
- for (int i = 0; i < 255; i++) {
- colors.push_back(Vec3b(d(gen), d(gen), d(gen)));
- }
- for (int i = 0; i < labels.rows; i++)
- {
- for (int j = 0; j < labels.cols; j++)
- {
- if (labels(i,j)>0) {
- destination(i, j) = colors[labels(i, j)];
- }
- else {
- destination(i, j) = Vec3b(255,255,255);
- }
- }
- }
- return destination;
- }
- void test_breadth_first_traversal() {
- char filename[MAX_PATH];
- openFileDlg(filename);
- Mat_<Vec3b> img;
- Mat_<uchar> src;
- src = imread(filename, CV_LOAD_IMAGE_GRAYSCALE);
- imshow("image", src);
- Mat_<uchar> labels = breadth_first_traversal(src);
- img = colorLabels(labels);
- imshow("labels", labels);
- imshow("color labels", img);
- waitKey(0);
- }
- Mat_<uchar> label_two_pass(Mat_<uchar> src){
- int di[8] = {0,-1,-1,-1,0,1,1,1};
- int dj[8] = {-1,-1,0,1,1,1,0,-1};
- int label = 0;
- int height = src.rows;
- int width = src.cols;
- Mat_<uchar> labels = Mat_<uchar>::zeros(height, width);
- std::vector<std::vector<int>> edges;
- for (int i = 0; i < height - 1; i++) {
- for (int j = 0; j < width; j++) {
- if (src(i, j) == 0 && labels(i, j) == 0) {
- std::vector<uchar> L;
- for (int k = 0; k < 4; k++) {
- Point neighbor(i + di[k], j + dj[k]);
- if (neighbor.x >= 0 && neighbor.x < src.rows && neighbor.y >= 0 && neighbor.y < src.cols) {
- if (labels(neighbor.x, neighbor.y) > 0) {
- L.push_back(labels(neighbor.x, neighbor.y));
- }
- }
- }
- if (L.size() == 0) {
- label++;
- labels(i, j) = label;
- }
- else {
- int x = *std::min_element(L.begin(), L.end());
- labels(i, j) = x;
- for (int k = 0; k < L.size(); k++) {
- if (L[k] != x) {
- edges.resize(label+1);
- edges[x].push_back(L[k]);
- edges[L[k]].push_back(x);
- }
- }
- }
- }
- }
- }
- int newLabel = 0;
- int * newLabels = new int[label + 1]();
- for (int i = 1; i <= label; i++) {
- if (newLabels[i] == 0) {
- newLabel++;
- std::queue<int> Q;
- newLabels[i] = newLabel;
- Q.push(i);
- while (!Q.empty()) {
- int x = Q.front();
- Q.pop();
- for (int y = 0; y < edges[x].size(); y++) {
- if (newLabels[edges[x][y]] == 0) {
- newLabels[edges[x][y]] = newLabel;
- Q.push(edges[x][y]);
- }
- }
- }
- }
- }
- for (int i = 0; i <= height - 1; i++) {
- for (int j = 0; j <= width - 1; j++) {
- labels(i, j) = newLabels[labels(i, j)];
- }
- }
- return labels;
- }
- void test_label_two_pass() {
- char filename[MAX_PATH];
- openFileDlg(filename);
- Mat_<uchar> src = imread(filename, CV_LOAD_IMAGE_GRAYSCALE);
- Mat_<uchar> labels = label_two_pass(src);
- Mat_<Vec3b> colors = colorLabels(labels);
- imshow("Source", src);
- imshow("Labels", labels);
- imshow("Colour", colors);
- waitKey();
- }
- std::vector<Point> traceBorder(Mat_<uchar> src, std::vector<int> *codeChain) {
- int rows = src.rows;
- int cols = src.cols;
- Mat_<Vec3b> dst(rows, cols);
- int lastDir = 0;
- int di[8] = { 0,-1,-1,-1,0,1,1,1 };
- int dj[8] = { 1,1,0,-1,-1,-1,0,1 };
- int k = 0;
- lastDir = 7;
- std::vector<Point> border;
- for (int i = 0; i < rows; i++)
- {
- for (int j = 0; j < cols; j++)
- {
- if (src(i, j) < 254)
- {
- dst(i, j) = Vec3b(255, 0, 0);
- int k = 0;
- Point startingPoint(j, i);
- Point lastpoint(j, i);
- Point neighbor(-1, -1);
- while (startingPoint != neighbor)
- {
- k = 0;
- if (lastDir % 2 == 0)
- {
- lastDir = (lastDir + 7) % 8;
- }
- else
- {
- lastDir = (lastDir + 6) % 8;
- }
- while (k < 8)
- {
- neighbor = Point(lastpoint.x + dj[lastDir], lastpoint.y + di[lastDir]);
- if (src(neighbor.y,neighbor.x) == src(i, j))
- {
- border.push_back(neighbor);
- codeChain->push_back(lastDir);
- break;
- }
- k++;
- lastDir = (lastDir + 1) % 8;
- }
- lastpoint = neighbor;
- }
- return border;
- }
- else
- {
- dst(i, j) = Vec3b(src(i, j), src(i, j), src(i, j));
- }
- }
- }
- return border;
- }
- void testBorderTracing()
- {
- int n;
- char fname[MAX_PATH];
- openFileDlg(fname);
- std::vector<int> codeChain;
- Mat_<uchar> src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
- Mat_<Vec3b> dst(src.rows, src.cols);
- std::vector<Point> border = traceBorder(src, &codeChain);
- std::vector<int> derivate;
- for (int i = 0; i < src.rows; i++)
- {
- for (int j = 0; j < src.cols; j++)
- {
- dst(i, j) = Vec3b(src(i, j), src(i, j), src(i, j));
- }
- }
- for (int i = 0; i < border.size(); i++)
- {
- dst(border[i]) = Vec3b(0,0,255);
- }
- for (int i = 0; i < codeChain.size(); i++) {
- printf("%d ",codeChain[i]);
- }
- imshow("src", src);
- imshow("dst", dst);
- waitKey(0);
- }
- Mat_<uchar> dillation(Mat_<uchar> src, Mat_<uchar> structure)
- {
- int rows = src.rows;
- int cols = src.cols;
- int width = structure.cols;
- int height = structure.rows;
- Mat_<uchar> dst(rows, cols, 255);
- for (int i = 0; i < rows; i++)
- {
- for (int j = 0; j < cols; j++)
- {
- if (src(i, j) == 0)
- {
- dst(i, j) = 0;
- for (int m = -height / 2; m <= height / 2; m++)
- {
- for (int n = -width / 2; n <= width / 2; n++)
- {
- Point neighbor(j + n, i + m);
- if (neighbor.x >= 0 && neighbor.x < cols && neighbor.y >= 0 && neighbor.y < rows)
- {
- if (structure(m + height / 2, n + width / 2) == 0)
- {
- dst(neighbor) = 0;
- }
- }
- }
- }
- }
- }
- }
- return dst;
- }
- Mat_<uchar> erosion(Mat_<uchar> src, Mat_<uchar> structure)
- {
- int rows = src.rows;
- int cols = src.cols;
- int width = structure.cols;
- int height = structure.rows;
- Mat_<uchar> dst(rows, cols, 255);
- int di[8] = { -1, 0, 1, 0, -1, 1, 1, -1 };
- int dj[8] = { 0, -1, 0, 1, -1, -1, 1, 1 };
- for (int i = 0; i < rows; i++)
- {
- for (int j = 0; j < cols; j++)
- {
- if (src(i, j) == 0)
- {
- dst(i, j) = 0;
- for (int m = -height / 2; m <= height / 2; m++)
- {
- for (int n = -width / 2; n <= width / 2; n++)
- {
- Point neighbor(j + n, i + m);
- if (neighbor.x >= 0 && neighbor.x < cols && neighbor.y >= 0 && neighbor.y < rows)
- {
- if (structure(m + height / 2, n + width / 2) == 0 && src(neighbor) == 255)
- {
- dst(i, j) = 255;
- }
- }
- }
- }
- }
- }
- }
- return dst;
- }
- void testErosion()
- {
- char fname[MAX_PATH];
- openFileDlg(fname);
- Mat_<uchar> src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
- Mat_<uchar> structure(3, 3);
- structure(0, 0) = 255;
- structure(0, 1) = 0;
- structure(0, 2) = 255;
- structure(1, 0) = 0;
- structure(1, 1) = 0;
- structure(1, 2) = 0;
- structure(2, 0) = 255;
- structure(2, 1) = 0;
- structure(2, 2) = 255;
- Mat_<uchar> dst = erosion(src, structure);
- imshow("original", src);
- imshow("eroded", dst);
- waitKey(0);
- }
- void testDillation()
- {
- char fname[MAX_PATH];
- openFileDlg(fname);
- Mat_<uchar> src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
- Mat_<uchar> structure(3, 3);
- structure(0, 0) = 255;
- structure(0, 1) = 0;
- structure(0, 2) = 255;
- structure(1, 0) = 0;
- structure(1, 1) = 0;
- structure(1, 2) = 0;
- structure(2, 0) = 255;
- structure(2, 1) = 0;
- structure(2, 2) = 255;
- Mat_<uchar> dst = dillation(src, structure);
- imshow("original", src);
- imshow("dillated", dst);
- waitKey(0);
- }
- Mat_<uchar> opening(Mat_<uchar> src, Mat_<uchar> structure)
- {
- int rows = src.rows;
- int cols = src.cols;
- Mat_<uchar> dst(rows,cols);
- Mat_<uchar> buffer = erosion(src, structure);
- dst = dillation(buffer, structure);
- return dst;
- }
- Mat_<uchar> closing(Mat_<uchar> src, Mat_<uchar> structure)
- {
- int rows = src.rows;
- int cols = src.cols;
- Mat_<uchar> dst(rows,cols);
- Mat_<uchar> buffer = dillation(src, structure);
- dst = erosion(buffer, structure);
- return dst;
- }
- void testOpening()
- {
- char fname[MAX_PATH];
- openFileDlg(fname);
- Mat_<uchar> src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
- Mat_<uchar> structure(3, 3);
- structure(0, 0) = 255;
- structure(0, 1) = 0;
- structure(0, 2) = 255;
- structure(1, 0) = 0;
- structure(1, 1) = 0;
- structure(1, 2) = 0;
- structure(2, 0) = 255;
- structure(2, 1) = 0;
- structure(2, 2) = 255;
- Mat_<uchar> dst = opening(src, structure);
- imshow("original", src);
- imshow("opened", dst);
- waitKey(0);
- }
- void testClosing()
- {
- char fname[MAX_PATH];
- openFileDlg(fname);
- Mat_<uchar> src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
- Mat_<uchar> structure(3, 3);
- structure(0, 0) = 255;
- structure(0, 1) = 0;
- structure(0, 2) = 255;
- structure(1, 0) = 0;
- structure(1, 1) = 0;
- structure(1, 2) = 0;
- structure(2, 0) = 255;
- structure(2, 1) = 0;
- structure(2, 2) = 255;
- Mat_<uchar> dst = closing(src, structure);
- imshow("original", src);
- imshow("closed", dst);
- waitKey(0);
- }
- Mat_<uchar> difference(Mat_<uchar> A, Mat_<uchar> B)
- {
- int rows = A.rows;
- int cols = A.cols;
- Mat_<uchar> dst(rows, cols);
- for (int i = 0; i < rows; i++)
- {
- for (int j = 0; j < cols; j++)
- {
- if (A(i, j) == B(i, j))
- {
- dst(i, j) = 255;
- }
- else
- {
- dst(i, j) = A(i, j);
- }
- }
- }
- return dst;
- }
- Mat_<uchar> boundaryExtraction(Mat_<uchar> src, Mat_<uchar> structure)
- {
- Mat_<uchar> eroded = erosion(src, structure);
- Mat_<uchar> boundary = difference(src, eroded);
- return boundary;
- }
- void testBoundaryExtraction()
- {
- char fname[MAX_PATH];
- openFileDlg(fname);
- Mat_<uchar> src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
- Mat_<uchar> dst(src.rows, src.cols);
- Mat_<uchar> structure(3, 3);
- structure(0, 0) = 0;
- structure(0, 1) = 0;
- structure(0, 2) = 0;
- structure(1, 0) = 0;
- structure(1, 1) = 0;
- structure(1, 2) = 0;
- structure(2, 0) = 0;
- structure(2, 1) = 0;
- structure(2, 2) = 0;
- dst = boundaryExtraction(src, structure);
- imshow("original", src);
- imshow("boundary", dst);
- waitKey(0);
- }
- int main()
- {
- int op;
- do
- {
- system("cls");
- destroyAllWindows();
- printf("Menu:\n");
- printf(" 1 - Open image\n");
- printf(" 2 - Open BMP images from folder\n");
- printf(" 3 - Image negative - diblook style\n");
- printf(" 4 - BGR->HSV\n");
- printf(" 5 - Resize image\n");
- printf(" 6 - Canny edge detection\n");
- printf(" 7 - Edges in a video sequence\n");
- printf(" 8 - Snap frame from live video\n");
- printf(" 9 - Mouse callback demo\n");
- printf(" 10 - Lab2 Copy RGB\n");
- printf(" 11 - Lab2 Convert to grayscale\n");
- printf(" 12 - Lab2 Convert to binary\n");
- printf(" 13 - Lab2 Compute HSV\n");
- printf(" 14 - Lab4 Object properties\n");
- printf(" 15 - Lab 3 show histogram\n");
- printf(" 16 - Lab3 show bins histogram\n");
- printf(" 17 - Lab3 multilevel thresholding\n");
- printf(" 18 - Lab5 breadth first traversal\n");
- printf(" 19- Lab5 label two pass\n");
- printf(" 20- Lab6 border tracing\n");
- printf(" 21 - Lab7 dillation\n");
- printf(" 22 - Lab7 erosion\n");
- printf(" 23 - Lab7 opening\n");
- printf(" 24 - Lab7 closing\n");
- printf(" 25 - Lab7 boundary extraction\n");
- printf(" 0 - Exit\n\n");
- printf("Option: ");
- scanf("%d",&op);
- switch (op)
- {
- case 1:
- testOpenImage();
- break;
- case 2:
- testOpenImagesFld();
- break;
- case 3:
- testParcurgereSimplaDiblookStyle(); //diblook style
- break;
- case 4:
- //testColor2Gray();
- testBGR2HSV();
- break;
- case 5:
- testResize();
- break;
- case 6:
- testCanny();
- break;
- case 7:
- testVideoSequence();
- break;
- case 8:
- testSnap();
- break;
- case 9:
- testMouseClick();
- break;
- case 10:
- copy_RGB();
- break;
- case 11:
- convert_to_grayscale();
- break;
- case 12:
- convert_to_binary();
- break;
- case 13:
- compute_HSV();
- break;
- case 14:
- testMouseClick();
- break;
- case 15:
- test_histogram();
- break;
- case 16:
- test_bins_histogram();
- break;
- case 17:
- testThresholding();
- break;
- case 18:
- test_breadth_first_traversal();
- break;
- case 19:
- test_label_two_pass();
- break;
- case 20:
- testBorderTracing();
- break;
- case 21:
- testDillation();
- break;
- case 22:
- testErosion();
- break;
- case 23:
- testOpening();
- break;
- case 24:
- testClosing();
- break;
- case 25:
- testBoundaryExtraction();
- break;
- }
- }
- while (op!=0);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement