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 <vector>
- #include <string>
- #include <queue>
- #include <random>
- #include<fstream>
- #define M_E 2.71828182845904523536
- std::queue<Point2i> Q;
- std::queue<int> QU;
- std::default_random_engine gen;
- std::uniform_int_distribution<int> d(0, 200);
- std::vector<int> v;
- 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 = MAX_PATH-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);
- }
- }
- }
- void MyCallBackFunc(int event, int x, int y, int flags, void* param)
- {
- Mat* src = (Mat*)param;
- if (event == CV_EVENT_LBUTTONDOWN)
- {
- Vec3b pixel = (*src).at<Vec3b>(y, x);
- Mat_<Vec3b> result = src->clone();
- /*Mat_<Vec3b> keeper(result.rows, result.cols);
- for (int i = 0; i < result.rows; ++i) {
- for (int j = 0; j < result.cols; ++j) {
- keeper(i, j) = result(i, j);
- }
- }*/
- Vec3b black;
- black[0] = 0;
- black[1] = 0;
- black[2] = 0;
- Vec3b red;
- red[0] = 0;
- red[1] = 0;
- red[2] = 255;
- // AREA
- int area = 0;
- for (int i = 0; i < result.rows; ++i) {
- for (int j = 0; j < result.cols; ++j) {
- if (result(i, j)[0] == pixel[0] && result(i, j)[1] == pixel[1] && result(i, j)[2] == pixel[2]) {
- result(i, j) = black;
- area++;
- }
- }
- }
- imshow("My Area", result);
- // CENTER OF MASS
- result = src->clone();
- int sumR = 0;
- int sumC = 0;
- for (int i = 0; i < result.rows; ++i) {
- for (int j = 0; j < result.cols; ++j) {
- if (result(i, j)[0] == pixel[0] && result(i, j)[1] == pixel[1] && result(i, j)[2] == pixel[2]) {
- sumR += i;
- sumC += j;
- }
- }
- }
- sumR /= area;
- sumC /= area;
- result(sumR, sumC) = black;
- result(sumR+1, sumC) = black;
- result(sumR+2, sumC) = black;
- result(sumR, sumC+1) = black;
- result(sumR, sumC+2) = black;
- result(sumR-1, sumC) = black;
- result(sumR-2, sumC) = black;
- result(sumR, sumC-1) = black;
- result(sumR, sumC-2) = black;
- imshow("My Center Of Mass", result);
- // AXIS OF ELONG
- result = src->clone();
- int S1 = 0, S2 = 0, S3 = 0;
- for (int i = 0; i < result.rows; ++i) {
- for (int j = 0; j < result.cols; ++j) {
- if (result(i, j)[0] == pixel[0] && result(i, j)[1] == pixel[1] && result(i, j)[2] == pixel[2]) {
- S1 += (i - sumR) * (j - sumC);
- S2 += pow((j - sumC), 2);
- S3 += pow((i - sumR), 2);
- }
- }
- }
- S1 *= 2;
- int S = S2 - S3;
- float phi = atan2(S1, S);
- phi /= 2;
- Point2i pc;
- pc.y = sumR;
- pc.x = sumC;
- Point2i pd;
- pd.y = sumR + 100 * sin(phi);
- pd.x = sumC + 100 * cos(phi);
- line(result, pc, pd, black, 1);
- imshow("My axis", result);
- // PERIMETER
- result = src->clone();
- int perimeter = 0;
- int diffListX[] = { 0, 0, -1, 1, 1, -1, -1, 1};
- int diffListY[] = { -1, 1, 0, 0, -1, 1, -1, 1};
- for (int i = 0; i < result.rows; ++i) {
- for (int j = 0; j < result.cols; ++j) {
- if (result(i, j)[0] == pixel[0] && result(i, j)[1] == pixel[1] && result(i, j)[2] == pixel[2]) {
- boolean Ok = false;
- for (int k = 0; k < 8; ++k) {
- int a = i + diffListX[k];
- int b = j + diffListY[k];
- if (result(a, b)[0] == 255 && result(a, b)[1] == 255 && result(a, b)[2] == 255) {
- Ok = true;
- }
- }
- if (Ok) {
- result(i, j) = black;
- perimeter++;
- }
- }
- }
- }
- imshow("My Perimeter", result);
- // THINNES
- float T = 4 * 3.14;
- T *= area;
- int Pat2 = pow(perimeter, 2);
- T /= Pat2;
- // ASPECT RATIO
- result = src->clone();
- float R;
- int minC = result.cols, minR = result.rows, maxC = 0, maxR = 0;
- for (int i = 0; i < result.rows; ++i) {
- for (int j = 0; j < result.cols; ++j) {
- if (result(i, j)[0] == pixel[0] && result(i, j)[1] == pixel[1] && result(i, j)[2] == pixel[2]) {
- if (minC > j) {
- minC = j;
- }
- if (minR > i) {
- minR = i;
- }
- if (maxC < j) {
- maxC = j;
- }
- if (maxR < i) {
- maxR = i;
- }
- }
- }
- }
- R =(float) (maxC - minC + 1) / (maxR - minR + 1);
- std::cout << R << '\n';
- Point2i p1;
- p1.y = minR;
- p1.x = minC;
- Point2i p2;
- p2.y = maxR;
- p2.x = minC;
- Point2i p3;
- p3.y = maxR;
- p3.x = maxC;
- Point2i p4;
- p4.y = minR;
- p4.x = maxC;
- line(result, p1, p2, black, 1);
- line(result, p2, p3, black, 1);
- line(result, p1, p4, black, 1);
- line(result, p3, p4, black, 1);
- imshow("My Aspect Ratio", result);
- // PROJECTIONS
- result = src->clone();
- for (int i = 0; i < result.rows; ++i) {
- int counter = 0;
- for (int j = 0; j < result.cols; ++j) {
- if (result(i, j)[0] == pixel[0] && result(i, j)[1] == pixel[1] && result(i, j)[2] == pixel[2]) {
- counter++;
- }
- }
- Point2i p1;
- p1.y = i;
- p1.x = result.cols;
- Point2i p2;
- p2.y = i;
- p2.x = result.cols - counter;
- line(result, p1, p2, black, 1);
- }
- for (int i = 0; i < result.cols; ++i) {
- int counter = 0;
- for (int j = 0; j < result.rows; ++j) {
- if (result(j, i)[0] == pixel[0] && result(j, i)[1] == pixel[1] && result(j, i)[2] == pixel[2]) {
- counter++;
- }
- }
- Point2i p1;
- p1.y = result.rows;
- p1.x = i;
- Point2i p2;
- p2.y = result.rows - counter;
- p2.x = i;
- line(result, p1, p2, black, 1);
- }
- imshow("My ", result);
- }
- }
- void testMouseClick()
- {
- Mat_<Vec3b> src;
- // Read image from file
- char fname[MAX_PATH];
- while (openFileDlg(fname))
- {
- src = imread(fname, CV_LOAD_IMAGE_COLOR);
- namedWindow("My Window", 1);
- imshow("My Window", src);
- setMouseCallback("My Window", MyCallBackFunc, &src);
- 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 copyRGBs() {
- Mat_<Vec3b> img = imread("Images/flowers_24bits.bmp", CV_LOAD_IMAGE_COLOR);
- Mat_<uchar> imgR(img.rows, img.cols);
- Mat_<uchar> imgG(img.rows, img.cols);
- Mat_<uchar> imgB(img.rows, img.cols);
- for (int i = 0; i < img.rows; ++i) {
- for (int j = 0; j < img.cols; ++j) {
- imgR(i, j) = img(i, j)[2];
- imgG(i, j) = img(i, j)[1];
- imgB(i, j) = img(i, j)[0];
- }
- }
- imshow("Red image", imgR);
- imshow("Green image", imgG);
- imshow("Blue image", imgB);
- waitKey(0);
- }
- void fromColorToRGB() {
- Mat_<Vec3b> img = imread("Images/kids.bmp", CV_LOAD_IMAGE_COLOR);
- Mat_<uchar> result(img.rows, img.cols);
- for (int i = 0; i < img.rows; ++i) {
- for (int j = 0; j < img.cols; ++j) {
- result(i, j) = (img(i, j)[0] + img(i, j)[1] + img(i, j)[2]) / 3;
- }
- }
- imshow("Gray image", result);
- Mat_<uchar> resultCVT(img.rows, img.cols);
- cvtColor(img, resultCVT, CV_RGB2GRAY);
- imshow("CVT", resultCVT);
- waitKey(0);
- }
- void convertBlackAndWhite(int t) {
- Mat_<uchar> img = imread("Images/eight.bmp", CV_LOAD_IMAGE_GRAYSCALE);
- Mat_<uchar> result(img.rows, img.cols);
- for (int i = 0; i < img.rows; ++i) {
- for (int j = 0; j < img.cols; ++j) {
- int aux = img(i, j);
- if (aux < t) {
- result(i, j) = 0;
- }
- else {
- result(i, j) = 255;
- }
- }
- }
- imshow("B&W image", result);
- waitKey(0);
- }
- void computeHSV() {
- Mat_<Vec3b> img = imread("Images/Lena_24bits.bmp", CV_LOAD_IMAGE_COLOR);
- Mat_<uchar> auxH(img.rows, img.cols);
- Mat_<uchar> auxS(img.rows, img.cols);
- Mat_<uchar> auxV(img.rows, img.cols);
- for (int i = 0; i < img.rows; ++i) {
- for (int j = 0; j < img.cols; ++j) {
- float r = (float) img(i, j)[2] / 255;
- float g = (float) img(i, j)[1] / 255;
- float b = (float) img(i, j)[0] / 255;
- float M = max(max(r, g), b);
- float m = min(min(r, g), b);
- float C = M - m;
- float V = M;
- float S;
- if(V != 0)
- S = C / V;
- else // grayscale
- S = 0;
- float H;
- 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 // grayscale
- H = 0;
- if(H < 0)
- H = H + 360;
- H = H * 255 / 360;
- S = S * 255;
- V = V * 255;
- auxH(i, j) = H;
- auxS(i, j) = S;
- auxV(i, j) = V;
- }
- }
- imshow("H", auxH);
- imshow("S", auxS);
- imshow("V", auxV);
- waitKey(0);
- }
- bool isInside(Mat img, int i, int j) {
- if (i >= img.rows) return false;
- if (j >= img.cols) return false;
- if (i < 0) return false;
- if (j < 0) return false;
- return true;
- }
- bool isInside(Mat_<uchar> img, int i, int j) {
- if (i >= img.rows) return false;
- if (j >= img.cols) return false;
- if (i < 0) return false;
- if (j < 0) return false;
- return true;
- }
- void calcHistogram(Mat_<uchar> img, int * hist, float * pdf, int m) {
- float M = (float)img.rows * img.cols;
- int bins = 256 / m;
- for (int i = 0; i < 256; ++i)
- hist[i] = 0;
- for (int i = 0; i < img.rows; ++i) {
- for (int j = 0; j < img.cols; ++j) {
- hist[img(i, j) / bins]++;
- }
- }
- for (int i = 0; i < 256; ++i) {
- float aux = (float)hist[i];
- //printf("%f/n", aux);
- pdf[i] = aux / M;
- //printf("%f", pdf[i]);
- }
- }
- void multilevelThresholding(int * hist, float * pdf, Mat_<uchar> image, Mat_<uchar> resultImage) {
- int WH = 5;
- int windowWidth = 2 * WH + 1;
- float TH = 0.0003;
- v.push_back(0);
- float average;
- for (int k = WH; k <= 255 - WH; ++k) {
- float sum = 0;
- for (int j = k - WH; j <= k + WH; ++j) {
- sum += pdf[j];
- }
- average = (float)sum / windowWidth;
- printf("AVG\n");
- bool isHigher = true;
- for (int j = k - WH; j <= k + WH; ++j) {
- if (pdf[k] < pdf[j]) {
- isHigher = false;
- }
- }
- if (isHigher) {
- printf("IS HIGHER\n\n\n");
- }
- if (pdf[k] > average + TH && isHigher) {
- v.push_back(k);
- printf("Pushback\n");
- }
- }
- v.push_back(255);
- for (int i = 0; i < image.rows; ++i) {
- for (int j = 0; j < image.cols; ++j) {
- //resultImage(i, j) = closestFromVector(image(i, j), v);
- int closest = v[0];
- for (auto const& it : v) {
- int currDifference = abs(closest - image(i, j));
- int newDifference = abs(it - image(i, j));
- if (newDifference < currDifference)
- closest = it;
- }
- resultImage(i, j) = closest;
- }
- }
- }
- void fsDithering(Mat_<uchar> source) {
- for (int i = 0; i < source.rows; ++i) {
- for (int j = 0; j < source.cols; ++j) {
- uchar oldPixel = source(i, j);
- int closest = v[0];
- for (auto const& it : v) {
- int currDifference = abs(closest - source(i, j));
- int newDifference = abs(it - source(i, j));
- if (newDifference < currDifference)
- closest = it;
- }
- uchar newPixel = closest;
- source(i, j) = newPixel;
- uchar error = oldPixel - newPixel;
- if (j + 1 < source.cols)
- source(i, j + 1) = source(i, j + 1) + (7 * error / 16);
- if (i + 1 < source.rows && j - 1 < 0)
- source(j - 1, i + 1) = source(j - 1, i + 1) + (3 * error / 16);
- if (i + 1 < source.rows)
- source(i + 1, j) = source(i + 1, j) + (5 * error / 16);
- if (i + 1 < source.rows && j + 1 < source.cols)
- source(j + 1, i + 1) = source(j + 1, i + 1) + (error / 16);
- }
- }
- imshow("FSD", source);
- waitKey(0);
- }
- Mat_<int> labelComponents(Mat_<uchar> src) {
- int diffListX[] = { 0, -1, 0, 1, -1, 1, -1, 1 };
- int diffListY[] = { -1, 0, 1, 0, -1, 1, 1, -1 };
- Mat_<int> toReturn(src.rows, src.cols);
- int label = 0;
- for (int i = 0; i < src.rows; ++i) {
- for (int j = 0; j < src.cols; ++j) {
- toReturn(i, j) = 0;
- }
- }
- for (int i = 0; i < src.rows; ++i) {
- for (int j = 0; j < src.cols; ++j) {
- if (src(i, j) == 0 && toReturn(i, j) == 0) {
- label++;
- toReturn(i, j) = label;
- Q = std::queue<Point2i>();
- Q.push({ i, j });
- while (!Q.empty()) {
- Point2i q = Q.front();
- Q.pop();
- for (int k = 0; k < 4; ++k) {
- int newX = q.x + diffListX[k];
- int newY = q.y + diffListY[k];
- if (newX >= 0 && newX < src.rows && newY >= 0 && newY < src.cols) {
- if (src(newX, newY) == 0 && toReturn(newX, newY) == 0) {
- toReturn(newX, newY) = label;
- Q.push({ newX, newY });
- }
- }
- }
- }
- }
- }
- }
- printf("%d", label);
- return toReturn;
- }
- Mat_<Vec3b> colorLabels(Mat_<int> src) {
- Mat_<Vec3b> toReturn(src.rows, src.cols);
- int maxLabel = -1;
- for (int i = 0; i < src.rows; ++i) {
- for (int j = 0; j < src.cols; ++j) {
- if (maxLabel < src(i, j)) {
- maxLabel = src(i, j);
- }
- toReturn(i, j)[0] = 255;
- toReturn(i, j)[1] = 255;
- toReturn(i, j)[2] = 255;
- }
- }
- Vec3b * colors = new Vec3b[maxLabel + 1];
- for (int i = 1; i <= maxLabel; ++i) {
- colors[i][0] = d(gen);
- colors[i][1] = d(gen);
- colors[i][1] = d(gen);
- }
- for (int i = 0; i < src.rows; ++i) {
- for (int j = 0; j < src.cols; ++j) {
- if (src(i, j)) {
- toReturn(i, j) = colors[src(i, j)];
- }
- }
- }
- free(colors);
- return toReturn;
- }
- void lab4() {
- Mat_<uchar> src;
- char fname[MAX_PATH];
- while (openFileDlg(fname))
- {
- src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
- namedWindow("My Window", 1);
- setMouseCallback("My Window", MyCallBackFunc, &src);
- imshow("My Window", src);
- Mat_<int> matWithComp = labelComponents(src);
- //imshow("Connected", matWithComp);
- Mat_<Vec3b> coloredImage = colorLabels(matWithComp);
- imshow("It's Complicated", coloredImage);
- waitKey(0);
- }
- }
- int getMinimum(std::vector<int> src) {
- int mini = -1;
- for (auto const& it : src) {
- if (it > mini)
- mini = it;
- }
- return mini;
- }
- Mat_<int> twoPass(Mat_<uchar> src) {
- int label = 0;
- Mat_<int> labels(src.rows, src.cols);
- int diffListX[] = { 0, -1, -1, -1 };
- int diffListY[] = { -1, -1, 0, 1 };
- /*for (int i = 0; i < src.rows; ++i) {
- for (int j = 0; j < src.cols; ++j) {
- }
- }*/
- labels.setTo(0);
- std::vector<std::vector<int>> edges(99999);
- for (int i = 0; i < src.rows; ++i) {
- for (int j = 0; j < src.cols; ++j) {
- if (src(i, j) == 0 && labels(i, j) == 0) {
- std::vector<int> L;
- for (int k = 0; k < 4; ++k) {
- int newI = i + diffListX[k];
- int newJ = j + diffListY[k];
- if (!(newI < 0 || newI >= src.rows || newJ < 0 || newJ >= src.cols)) {
- if (labels(newI, newJ) > 0) {
- L.push_back(labels(newI, newJ));
- }
- }
- }
- if (L.size() == 0) {
- label++;
- labels(i, j) = label;
- }
- else {
- int x = getMinimum(L);
- labels(i, j) = x;
- for (auto const& it : L) {
- if (x != it) {
- edges.resize(label + 2);
- edges[x].push_back(it);
- edges[it].push_back(x);
- }
- }
- }
- }
- }
- }
- int newLabel = 0;
- int * newLabels = new int[label + 2];
- for (int i = 0; i < label + 2; ++i) {
- newLabels[i] = 0;
- }
- for (int i = 1; i <= label; ++i) {
- if (newLabels[i] == 0) {
- newLabel++;
- QU = std::queue<int>();
- newLabels[i] = newLabel;
- QU.push(i);
- while (!QU.empty()) {
- int x = QU.front();
- QU.pop();
- for (auto const& it : edges[x]) {
- if (newLabels[it] == 0) {
- newLabels[it] = newLabel;
- QU.push(it);
- }
- }
- }
- }
- }
- for (int i = 0; i < src.rows; i++) {
- for (int j = 0; j < src.cols; ++j) {
- labels(i, j) = newLabels[labels(i, j)];
- }
- }
- return labels;
- }
- void lab4twoPass() {
- Mat_<uchar> src;
- char fname[MAX_PATH];
- while (openFileDlg(fname))
- {
- src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
- namedWindow("My Window", 1);
- setMouseCallback("My Window", MyCallBackFunc, &src);
- imshow("My Window", src);
- Mat_<int> matWithComp = twoPass(src);
- //imshow("Connected", matWithComp);
- Mat_<Vec3b> coloredImage = colorLabels(matWithComp);
- imshow("It's Complicated", coloredImage);
- waitKey(0);
- }
- }
- void drawWithChainCode() {
- std::ifstream myReadFile;
- myReadFile.open("Images/reconstruct.txt");
- int di[] = { 0, -1, -1, -1, 0, 1, 1, 1 };
- int dj[] = { 1, 1, 0, -1, -1, -1, 0, 1 };
- Mat_<uchar> result(1500, 1500);
- int startI, startJ, nr;
- if (myReadFile.is_open()) {
- myReadFile >> startI >> startJ >> nr;
- int x;
- for (int i = 0; i < nr; ++i) {
- myReadFile >> x;
- startI += di[x];
- startJ += dj[x];
- result(startI, startJ) = 0;
- }
- }
- myReadFile.close();
- imshow("RECREATA", result);
- waitKey(0);
- /*for (int i = 0; i < result.rows; ++i) {
- for (int j = 0; j < result.cols; ++j) {
- result(i, j) = 255;
- }
- }
- result(startI, startJ) = 0;
- for (int x : chain) {
- startI += di[x];
- startJ += dj[x];
- result(startI, startJ) = 0;
- }
- imshow("RECREATA", result);
- waitKey(0);*/
- }
- void borderTrace() {
- Mat_<uchar> src;
- // Read image from file
- char fname[MAX_PATH];
- while (openFileDlg(fname))
- {
- src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
- namedWindow("My Window", 1);
- imshow("My Window", src);
- int di[] = { 0, -1, -1, -1, 0, 1, 1, 1 };
- int dj[] = { 1, 1, 0, -1, -1, -1, 0, 1 };
- Mat_<uchar> result = src.clone();
- uchar background = result(0, 0);
- uchar color;
- std::vector<std::pair<int, int>> p;
- std::vector<int> c;
- int coordI, coordJ;
- for (int i = 0; i < result.rows; ++i) {
- for (int j = 0; j < result.cols; ++j) {
- if (result(i, j) != background) {
- color = result(i, j);
- coordI = i;
- coordJ = j;
- goto next;
- }
- }
- }
- next:
- int dir = 7;
- p.push_back(std::make_pair(coordI, coordJ));
- bool run = true;
- while (run) {
- if (dir % 2 == 0) {
- dir = (dir + 7) % 8;
- }
- else {
- dir = (dir + 6) % 8;
- }
- for (int k = 0; k < 8; ++k) {
- if (result(coordI + di[(dir + k) % 8], coordJ + dj[(dir + k) % 8]) == color) {
- p.push_back(std::make_pair(coordI + di[(dir + k) % 8], coordJ + dj[(dir + k) % 8]));
- coordI = coordI + di[(dir + k) % 8];
- coordJ = coordJ + dj[(dir + k) % 8];
- dir = (dir + k) % 8;
- c.push_back(dir);
- std::cout << dir << '\n';
- break;
- }
- }
- int size = (int) p.size();
- if (size > 2 && p.at(0).first == p.at(size - 2).first && p.at(0).second == p.at(size - 2).second && p.at(1).first == p.at(size - 1).first && p.at(1).second == p.at(size - 1).second) {
- run = false;
- }
- }
- Mat_<uchar> toShow(src.rows, src.cols);
- for (int i = 0; i < result.rows; ++i) {
- for (int j = 0; j < result.cols; ++j) {
- toShow(i, j) = 255;
- }
- }
- for (std::pair<int, int> pairr : p) {
- toShow(pairr.first, pairr.second) = 0;
- }
- std::vector<int> der;
- der.push_back((c.back() - c.front()) % 8);
- for (int z = 1; z < c.size(); ++z) {
- int result = (c.at(z) - c.at(z - 1)) % 8;
- if (result < 0) {
- der.push_back(result + 8);
- }
- else {
- der.push_back(result);
- }
- }
- for (int z : der) {
- std::cout << z << ' ';
- }
- imshow("RESULT", toShow);
- waitKey(0);
- }
- }
- void dilatate() {
- Mat_<uchar> input = imread("Images/Morphological_Op_Images/1_Dilate/reg1neg1_bw.bmp", CV_LOAD_IMAGE_GRAYSCALE);
- Mat_<uchar> result = input.clone();
- uchar background = input(0, 0);
- for (int i = 0; i < input.rows; ++i) {
- for (int j = 0; j < input.cols; ++j) {
- if (input(i, j) != background) {
- if(i+1 < input.rows)
- result(i+1, j) = input(i, j);
- if (i + 1 < input.rows && j + 1 < input.cols)
- result(i+1, j+1) = input(i, j);
- if(j + 1 < input.cols)
- result(i, j+1) = input(i, j);
- if (i - 1 >= 0 && j + 1 < input.cols)
- result(i-1, j+1) = input(i, j);
- if (i - 1 >= 0)
- result(i-1, j) = input(i, j);
- if (i - 1 >= 0 && j - 1 >= 0)
- result(i-1, j-1) = input(i, j);
- if(j - 1 >= 0)
- result(i, j-1) = input(i, j);
- if (i + 1 < input.rows && j - 1 >= 0)
- result(i+1, j-1) = input(i, j);
- }
- }
- }
- imshow("INPUT", input);
- imshow("RESULT", result);
- waitKey(0);
- }
- void calcHistogram(Mat_<uchar> img, int * hist) {
- float M = (float)img.rows * img.cols;
- for (int i = 0; i < 256; ++i)
- hist[i] = 0;
- for (int i = 0; i < img.rows; ++i) {
- for (int j = 0; j < img.cols; ++j) {
- hist[img(i, j)]++;
- }
- }
- }
- float meanValue(int* hist, float area) {
- int toReturn = 0;
- for (int i = 0; i < 256; ++i) {
- toReturn += i * hist[i];
- }
- return (float) toReturn / area;
- }
- float stdDerivation(int* hist, float meanValue, int dim) {
- double toReturn = 0;
- for (int i = 0; i < 256; ++i) {
- toReturn += pow((i - meanValue), 2) * hist[i];
- }
- std::cout << "Standard " << toReturn << '\n';
- float sq = sqrt((float)toReturn/dim);
- return sq;
- }
- int maxIntensity(int * hist) {
- for (int i = 255; i >= 0; ++i) {
- if (hist[i] != 0) {
- return i;
- }
- }
- return 0;
- }
- int minIntensity(int * hist) {
- for (int i = 0; i < 256; ++i) {
- if (hist[i] != 0) {
- return i;
- }
- }
- return 255;
- }
- void strechHist(int * hist, int* toReturn, int gMin, int gMax) {
- int minG = minIntensity(hist);
- int maxG = maxIntensity(hist);
- toReturn = new int[256];
- for (int i = 0; i < 256; ++i) {
- toReturn[i] = gMin + (hist[i] - minG) * (gMax - gMin) / (maxG - minG);
- }
- }
- void gammaHist(int * hist, int* toReturn, int gMin, int gMax) {
- }
- void lab8() {
- Mat_<uchar> src;
- // Read image from file
- char fname[MAX_PATH];
- while (openFileDlg(fname))
- {
- src = imread(fname, 0);
- imshow("Source Window", src);
- int * hist = new int[256];
- calcHistogram(src, hist);
- showHistogram("Mein Hist", hist, 256, 256);
- float mv = meanValue(hist, src.rows * src.cols);
- float sd = stdDerivation(hist, mv, src.rows * src.cols);
- int mnIntensity = minIntensity(hist);
- int mxIntensity = maxIntensity(hist);
- std::cout << "Mean value " << mv << '\n';
- std::cout << "Standard derivation " << sd << '\n';
- std::cout << "Min Intensity " << mnIntensity << '\n';
- std::cout << "Max Intensity " << mxIntensity << '\n';
- int T = 156;
- int Tf;
- int error = 1;
- do {
- int N1 = 0;
- for (int i = mnIntensity; i < T+1; ++i) {
- N1 += hist[i];
- }
- int N2 = 0;
- for (int i = T + 1; i < mxIntensity; ++i) {
- N2 += hist[i];
- }
- int G1 = 0;
- for (int i = mnIntensity; i < T+1; ++i) {
- G1 += hist[i] * i;
- }
- int G2 = 0;
- for (int i = T + 1; i < mxIntensity; ++i) {
- G2 += hist[i] * i;
- }
- G1 /= N1;
- G2 /= N2;
- Tf = T;
- T = (G1 + G2) / 2;
- } while (abs(T - Tf) > error);
- std::cout << "DDDDDDD " << T << '\n';
- Mat_<uchar> result(src.rows, src.cols);
- for (int i = 0; i < src.rows; ++i) {
- for (int j = 0; j < src.cols; ++j) {
- if (src(i, j) < T) {
- result(i, j) = 0;
- }
- else {
- result(i, j) = 255;
- }
- }
- }
- imshow("THR", result);
- int* strech = new int[256];
- strechHist(hist, strech, 100, 200);
- showHistogram("Mein Hist2", strech, 256, 256);
- waitKey(0);
- }
- }
- Mat_<float> convolute(Mat_<uchar> source, Mat_<float> h) {
- Mat_<float> toReturn(source.rows, source.cols);
- int k = (h.rows - 1) / 2;
- for (int i = 0; i < source.rows; ++i) {
- for (int j = 0; j < source.cols; ++j) {
- float sum = 0;
- /*for (int l = i - k; l < i + k; ++l) {
- for (int m = j - k; m < j + k; ++m) {
- if (isInside(source, l, m)) {
- sum += source(l, m) * h(i)
- }
- }
- }*/
- for (int l = 0; l < h.rows; ++l) {
- for (int m = 0; m < h.cols; ++m) {
- if (isInside(source, i + l - k, j + m - k)) {
- sum += (float)(h(l, m) * source(i + l - k, j + m - k));
- }
- }
- }
- toReturn(i, j) = sum;
- }
- }
- return toReturn;
- }
- Mat_<uchar> normalizeMat(Mat_<float> toNormalize, float minimul, float maximul) {
- Mat_<uchar> toReturn(toNormalize.rows, toNormalize.cols);
- for (int i = 0; i < toNormalize.rows; ++i) {
- for (int j = 0; j < toNormalize.cols; ++j) {
- toReturn(i, j) = ((toNormalize(i, j) - minimul) * 255) / (maximul - minimul);
- }
- }
- return toReturn;
- }
- float getMaxValue(Mat_<float> h) {
- float toReturn = 0;
- for (int i = 0; i < h.rows; ++i) {
- for (int j = 0; j < h.cols; ++j) {
- if (h(i, j) > 0) {
- toReturn += h(i, j);
- }
- }
- }
- return (toReturn * 255);
- }
- float getMinValue(Mat_<float> h) {
- float toReturn = 0;
- for (int i = 0; i < h.rows; ++i) {
- for (int j = 0; j < h.cols; ++j) {
- if (h(i, j) < 0) {
- toReturn += h(i, j);
- }
- }
- }
- return (toReturn * 255);
- }
- void lab9() {
- Mat_<uchar> src;
- // Read image from file
- char fname[MAX_PATH];
- while (openFileDlg(fname))
- {
- src = imread(fname, 0);
- Mat_<float> h(3, 3);
- for (int i = 0; i < h.rows; ++i) {
- for (int j = 0; j < h.cols; ++j) {
- h(i, j) = (float)-1;
- }
- }
- h(1, 1) = 8;
- Mat_<float> convoluted(src.rows, src.cols);
- convoluted = convolute(src, h);
- imshow("Conv", convoluted);
- Mat_<uchar> result(convoluted.rows, convoluted.cols);
- int a = getMinValue(h);
- a *= -1;
- int b = getMaxValue(h);
- result = normalizeMat(convoluted, 0, max(a,b));
- imshow("Res", result);
- waitKey(0);
- }
- }
- void centering_transform(Mat img) {
- //expects floating point image
- for (int i = 0; i < img.rows; i++) {
- for (int j = 0; j < img.cols; j++) {
- img.at<float>(i, j) = ((i + j) & 1) ? -img.at<float>(i, j) : img.at<float>(i, j);
- }
- }
- }
- Mat generic_frequency_domain_filter(Mat src) {
- //convert input image to float image
- Mat srcf;
- src.convertTo(srcf, CV_32FC1);
- //centering transformation
- centering_transform(srcf);
- //perform forward transform with complex image output
- Mat fourier;
- dft(srcf, fourier, DFT_COMPLEX_OUTPUT);
- //split into real and imaginary channels
- Mat channels[] = { Mat::zeros(src.size(), CV_32F), Mat::zeros(src.size(), CV_32F) };
- split(fourier, channels); // channels[0] = Re(DFT(I)), channels[1] = Im(DFT(I))
- //calculate magnitude and phase in floating point images mag and phi
- Mat mag, phi;
- magnitude(channels[0], channels[1], mag);
- phase(channels[0], channels[1], phi);
- //display the phase and magnitude images here
- imshow("MAG", mag);
- imshow("PHS", phi);
- //insert filtering operations on Fourier coefficients here
- int centerI = src.rows / 2;
- int centerJ = src.cols / 2;
- /*for (int i = 0; i < src.rows; ++i) {
- for (int j = 0; j < src.cols; ++j) {
- if (sqrt(pow((centerI - i), 2) + pow((centerJ - j), 2)) >= 20)
- mag.at<float>(i, j) = 0.f;
- }
- }*/
- for (int i = 0; i < src.rows; ++i) {
- for (int j = 0; j < src.cols; ++j) {
- mag.at<float>(i, j) = mag.at<float>(i, j) * pow(M_E, -1 * (pow((mag.cols / 2 - i), 2) + pow(mag.rows / 2 - j, 2))/ 400);
- }
- }
- //store in real part in channels[0] and imaginary part in channels[1]
- for (int i = 0; i < src.rows; ++i) {
- for (int j = 0; j < src.cols; ++j) {
- channels[0].at<float>(i, j) = mag.at<float>(i, j) * cos(phi.at<float>(i, j));
- channels[1].at<float>(i, j) = mag.at<float>(i, j) * sin(phi.at<float>(i, j));
- }
- }
- //perform inverse transform and put results in dstf
- Mat dst, dstf;
- merge(channels, 2, fourier);
- dft(fourier, dstf, DFT_INVERSE | DFT_REAL_OUTPUT | DFT_SCALE);
- //inverse centering transformation
- centering_transform(dstf);
- //normalize the result and put in the destination image
- normalize(dstf, dst, 0, 255, NORM_MINMAX, CV_8UC1);
- imshow("DST", dst);
- return dst;
- }
- void lab92() {
- Mat src;
- // Read image from file
- char fname[MAX_PATH];
- while (openFileDlg(fname))
- {
- src = imread(fname, 0);
- generic_frequency_domain_filter(src);
- imshow("Opened Image", src);
- waitKey(0);
- }
- }
- Mat_<float> constructFilter(int w) {
- Mat_<float> toReturn(w, w);
- float o = w / 6.0;
- for (int i = 0; i < w; ++i) {
- for (int j = 0; j < w; ++j) {
- toReturn(i, j) = 1 / (2 * PI * pow(o, 2)) * pow(M_E, -(pow(i - w / 2, 2) + pow(j - w / 2, 2) / (2 * pow(o, 2))));
- std::cout << toReturn(i, j) << ' ';
- }
- std::cout << '\n';
- }
- return toReturn;
- }
- void lab10() {
- Mat_<uchar> src;
- // Read image from file
- char fname[MAX_PATH];
- while (openFileDlg(fname))
- {
- src = imread(fname, 0);
- double t = (double)getTickCount();
- Mat_<float> matConvoluted = convolute(src, constructFilter(5));
- Mat_<uchar> result = normalizeMat(matConvoluted, 0, 255);
- t = ((double)getTickCount() - t) / getTickFrequency();
- std::cout << "\nTime was:\n" << t * 1000;
- imshow("Src", src);
- imshow("Res", result);
- waitKey(0);
- }
- }
- void lab10_2() {
- Mat_<uchar> src;
- // Read image from file
- char fname[MAX_PATH];
- while (openFileDlg(fname))
- {
- src = imread(fname, 0);
- double t = (double)getTickCount();
- int w = 5;
- float o = w / 6.0;
- Mat_<float> filter = constructFilter(w);
- Mat_<float> Gx(1, w);
- Mat_<float> Gy(w, 1);
- for (int i = 0; i < w; ++i) {
- Gx(0, i) = 1 / (sqrt(2 * PI) * o) * pow(M_E, -(pow(i - w / 2, 2) / (2 * pow(o, 2))));
- Gy(i, 0) = 1 / (sqrt(2 * PI) * o) * pow(M_E, -(pow(i - w / 2, 2) / (2 * pow(o, 2))));
- }
- Mat_<uchar> mat_gx = convolute(src, Gx);
- Mat_<uchar> mat_gy = convolute(mat_gx, Gy);
- t = ((double)getTickCount() - t) / getTickFrequency();
- std::cout << "\nTime was:\n" << t * 1000;
- imshow("Gx", mat_gx);
- imshow("Gy", mat_gy);
- //Mat_<uchar> mat_gy = convolute(mat_gx, fil)
- imshow("Src2", src);
- waitKey(0);
- }
- }
- void lab10_3() {
- Mat_<uchar> src;
- // Read image from file
- char fname[MAX_PATH];
- while (openFileDlg(fname))
- {
- src = imread(fname, 0);
- Mat_<uchar> result(src.rows, src.cols);
- int w = 5;
- for (int i = 0; i < src.rows; ++i) {
- for (int j = 0; j < src.cols; ++j) {
- std::vector<int> v;
- for (int ii = 0; ii < w; ++ii) {
- for (int jj = 0; jj < w; ++jj) {
- if (isInside(src, i+ii, j+jj)) {
- v.push_back(src(i+ii, j+jj));
- }
- }
- }
- std::sort(v.begin(), v.end());
- result(i, j) = v.at(v.size() / 2);
- }
- }
- imshow("Src3", src);
- imshow("Result", result);
- waitKey(0);
- }
- }
- //Mat_<float> toMat_(Mat source) {
- // Mat_<float> toReturn(source.rows, source.cols);
- // for (int i = 0; i < source.rows; i++) {
- // for (int j = 0; j < source.cols; ++j) {
- //
- // }
- // }
- //}
- Mat_<uchar> three_way(Mat_<float> src) {
- Mat_<uchar> res(src.rows, src.cols);
- for (int i = 0; i < src.rows; i++) {
- for (int j = 0; j < src.cols; j++) {
- if (src(i, j) < 90) {
- res(i, j) = 0;
- }
- else {
- if (src(i, j) < 180) {
- res(i, j) = 128;
- }
- else {
- res(i, j) = 255;
- }
- }
- }
- }
- return res;
- }
- void lab11() {
- Mat_<uchar> src;
- // Read image from file
- char fname[MAX_PATH];
- while (openFileDlg(fname))
- {
- src = imread(fname, 0);
- float dx[9] = {
- (float)-1, (float)0, (float)1,
- (float)-2, (float)0, (float)2,
- (float)-1, (float)0, (float)1
- };
- float dy[9] = {
- (float)1, (float)2, (float)1,
- (float)0, (float)0, (float)0,
- (float)-1, (float)-2, (float)-1
- };
- int neighi[] = { 0, -1, -1, -1, 0, 1, 1, 1 };
- int neighj[] = { 1, 1, 0, -1, -1, -1, 0, 1 };
- Mat theDx(3, 3, CV_32FC1, dx);
- Mat theDy(3, 3, CV_32FC1, dy);
- Mat_<float> resDX = convolute(src, theDx);
- Mat_<float> resDY = convolute(src, theDy);
- imshow("DX", abs(resDX / 255));
- imshow("DY", abs(resDY / 255));
- Mat_<float> angle(src.rows, src.cols);
- Mat_<float> magnitude(src.rows, src.cols);
- for (int i = 0; i < src.rows; ++i) {
- for (int j = 0; j < src.cols; ++j) {
- angle(i, j) = atan2(resDY(i, j), resDX(i, j));
- magnitude(i, j) = sqrt(resDX(i, j) * resDX(i, j) + resDY(i, j) * resDY(i, j));
- }
- }
- imshow("Angle", abs(angle / 2 * PI));
- imshow("Magnitude", magnitude / 255);
- Mat_<float> magnitudeFinal(src.rows, src.cols);
- for (int i = 0; i < src.rows; ++i) {
- for (int j = 0; j < src.cols; ++j) {
- float value;
- if (angle(i, j) < 0) {
- value = angle(i, j) + (2 * PI);
- }
- else {
- value = angle(i, j);
- }
- int beta = floor((value * 8 / (2 * PI)) + 0.5);
- beta %= 8;
- int otherBeta = (beta + 4) % 8;
- //bool marked = false;
- if (!isInside(src, i + neighi[beta], j + neighj[beta]) || !isInside(src, i + neighi[otherBeta], j + neighj[otherBeta])) {
- magnitudeFinal(i, j) = magnitude(i, j);
- }
- else {
- if (magnitude(i + neighi[beta], j + neighj[beta]) >= magnitude(i, j) || magnitude(i + neighi[otherBeta], j + neighj[otherBeta]) >= magnitude(i, j)) {
- magnitudeFinal(i, j) = 0;
- }
- else {
- magnitudeFinal(i, j) = magnitude(i, j);
- }
- }
- }
- }
- Mat_<uchar> three = three_way(magnitudeFinal);
- Mat_<uchar> link = three.clone();
- for (int i = 0; i < link.rows; i++) {
- for (int j = 0; j < link.cols; j++) {
- if (link(i, j) == 255) {
- std::queue<Point2i> Queue;
- Queue.push(Point2i(i, j));
- while (!Queue.empty()) {
- Point2i pixel = Queue.front();
- Queue.pop();
- for (int k = 0; k < 8; k++) {
- if (isInside(link, pixel.x + neighi[k], pixel.y + neighj[k])) {
- if (link(pixel.x + neighi[k], pixel.y + neighj[k]) == 128) {
- link(pixel.x + neighi[k], pixel.y + neighj[k]) = 255;
- Queue.push(Point2i(pixel.x + neighi[k], pixel.y + neighj[k]));
- }
- }
- }
- }
- }
- }
- }
- for (int i = 0; i < link.rows; i++) {
- for (int j = 0; j < link.cols; j++) {
- if (link(i, j) == 128) {
- link(i, j) = 0;
- }
- }
- }
- imshow("MAG FINAL", magnitudeFinal / 255);
- imshow("Three way", three);
- imshow("link", link);
- imshow("src", src);
- waitKey(0);
- }
- }
- void lab12() {
- Mat_<uchar> src;
- // Read image from file
- char fname[MAX_PATH];
- while (openFileDlg(fname))
- {
- src = imread(fname, 0);
- Mat_<uchar> result = src.clone();
- int neigi[] = { 0, -1, 0, 1 };
- int neigj[] = { 1, 0, -1, 0 };
- uchar bg = 255;
- for (int i = 0; i < src.rows; ++i) {
- for (int j = 0; j < src.cols; ++j) {
- boolean insider = true;
- for (int k = 0; k < 4; ++k) {
- if (isInside(src, i + neigi[k], j + neigj[k])) {
- if (src(i + neigi[k], j + neigj[k]) == bg) {
- insider = false;
- }
- }
- }
- if (insider) {
- result(i, j) = src(i, j);
- }
- else {
- result(i, j) = bg;
- }
- }
- }
- imshow("Result", result);
- imshow("src", src);
- waitKey(0);
- }
- }
- int main()
- {
- //lab12 e doar erosion
- //lab12();
- //lab11();
- //lab10();
- //lab10_2();
- //lab10_3();
- //lab9();
- //lab92();
- //lab8();
- //dilatate();
- //drawWithChainCode();
- //borderTrace();
- //testMouseClick();
- //copyRGBs();
- //fromColorToRGB();
- //int threshold;
- //scanf("%d", &threshold);
- //printf("%d", threshold);
- //convertBlackAndWhite(threshold);
- //computeHSV();
- /*Mat img = imread("Images/Lena_24bits.bmp", CV_LOAD_IMAGE_COLOR);
- if (isInside(img, 50, 50)) {
- printf("It is");
- }
- else {
- printf("It's not");
- }*/
- //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(" 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;
- // }
- //}
- //while (op!=0);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement