Advertisement
Guest User

Untitled

a guest
May 26th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 44.30 KB | None | 0 0
  1. // OpenCVApplication.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include "common.h"
  6. #include <vector>
  7. #include <string>
  8. #include <queue>
  9. #include <random>
  10. #include<fstream>
  11. #define M_E 2.71828182845904523536
  12.  
  13.  
  14. std::queue<Point2i> Q;
  15. std::queue<int> QU;
  16. std::default_random_engine gen;
  17. std::uniform_int_distribution<int> d(0, 200);
  18.  
  19. std::vector<int> v;
  20.  
  21. void testOpenImage()
  22. {
  23. char fname[MAX_PATH];
  24. while(openFileDlg(fname))
  25. {
  26. Mat src;
  27. src = imread(fname);
  28. imshow("image",src);
  29. waitKey();
  30. }
  31. }
  32.  
  33. void testOpenImagesFld()
  34. {
  35. char folderName[MAX_PATH];
  36. if (openFolderDlg(folderName)==0)
  37. return;
  38. char fname[MAX_PATH];
  39. FileGetter fg(folderName,"bmp");
  40. while(fg.getNextAbsFile(fname))
  41. {
  42. Mat src;
  43. src = imread(fname);
  44. imshow(fg.getFoundFileName(),src);
  45. if (waitKey()==27) //ESC pressed
  46. break;
  47. }
  48. }
  49.  
  50. void testImageOpenAndSave()
  51. {
  52. Mat src, dst;
  53.  
  54. src = imread("Images/Lena_24bits.bmp", CV_LOAD_IMAGE_COLOR); // Read the image
  55.  
  56. if (!src.data) // Check for invalid input
  57. {
  58. printf("Could not open or find the image\n");
  59. return;
  60. }
  61.  
  62. // Get the image resolution
  63. Size src_size = Size(src.cols, src.rows);
  64.  
  65. // Display window
  66. const char* WIN_SRC = "Src"; //window for the source image
  67. namedWindow(WIN_SRC, CV_WINDOW_AUTOSIZE);
  68. cvMoveWindow(WIN_SRC, 0, 0);
  69.  
  70. const char* WIN_DST = "Dst"; //window for the destination (processed) image
  71. namedWindow(WIN_DST, CV_WINDOW_AUTOSIZE);
  72. cvMoveWindow(WIN_DST, src_size.width + 10, 0);
  73.  
  74. cvtColor(src, dst, CV_BGR2GRAY); //converts the source image to a grayscale one
  75.  
  76. imwrite("Images/Lena_24bits_gray.bmp", dst); //writes the destination to file
  77.  
  78. imshow(WIN_SRC, src);
  79. imshow(WIN_DST, dst);
  80.  
  81. printf("Press any key to continue ...\n");
  82. waitKey(0);
  83. }
  84.  
  85. void testNegativeImage()
  86. {
  87. char fname[MAX_PATH];
  88. while(openFileDlg(fname))
  89. {
  90. double t = (double)getTickCount(); // Get the current time [s]
  91.  
  92. Mat src = imread(fname,CV_LOAD_IMAGE_GRAYSCALE);
  93. int height = src.rows;
  94. int width = src.cols;
  95. Mat dst = Mat(height,width,CV_8UC1);
  96. // Asa se acceseaaza pixelii individuali pt. o imagine cu 8 biti/pixel
  97. // Varianta ineficienta (lenta)
  98. for (int i=0; i<height; i++)
  99. {
  100. for (int j=0; j<width; j++)
  101. {
  102. uchar val = src.at<uchar>(i,j);
  103. uchar neg = MAX_PATH-val;
  104. dst.at<uchar>(i,j) = neg;
  105. }
  106. }
  107.  
  108. // Get the current time again and compute the time difference [s]
  109. t = ((double)getTickCount() - t) / getTickFrequency();
  110. // Print (in the console window) the processing time in [ms]
  111. printf("Time = %.3f [ms]\n", t * 1000);
  112.  
  113. imshow("input image",src);
  114. imshow("negative image",dst);
  115. waitKey();
  116. }
  117. }
  118.  
  119. void testParcurgereSimplaDiblookStyle()
  120. {
  121. char fname[MAX_PATH];
  122. while (openFileDlg(fname))
  123. {
  124. Mat src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
  125. int height = src.rows;
  126. int width = src.cols;
  127. Mat dst = src.clone();
  128.  
  129. double t = (double)getTickCount(); // Get the current time [s]
  130.  
  131. // the fastest approach using the “diblook style”
  132. uchar *lpSrc = src.data;
  133. uchar *lpDst = dst.data;
  134. int w = (int) src.step; // no dword alignment is done !!!
  135. for (int i = 0; i<height; i++)
  136. for (int j = 0; j < width; j++) {
  137. uchar val = lpSrc[i*w + j];
  138. lpDst[i*w + j] = 255 - val;
  139. }
  140.  
  141. // Get the current time again and compute the time difference [s]
  142. t = ((double)getTickCount() - t) / getTickFrequency();
  143. // Print (in the console window) the processing time in [ms]
  144. printf("Time = %.3f [ms]\n", t * 1000);
  145.  
  146. imshow("input image",src);
  147. imshow("negative image",dst);
  148. waitKey();
  149. }
  150. }
  151.  
  152. void testColor2Gray()
  153. {
  154. char fname[MAX_PATH];
  155. while(openFileDlg(fname))
  156. {
  157. Mat src = imread(fname);
  158.  
  159. int height = src.rows;
  160. int width = src.cols;
  161.  
  162. Mat dst = Mat(height,width,CV_8UC1);
  163.  
  164. // Asa se acceseaaza pixelii individuali pt. o imagine RGB 24 biti/pixel
  165. // Varianta ineficienta (lenta)
  166. for (int i=0; i<height; i++)
  167. {
  168. for (int j=0; j<width; j++)
  169. {
  170. Vec3b v3 = src.at<Vec3b>(i,j);
  171. uchar b = v3[0];
  172. uchar g = v3[1];
  173. uchar r = v3[2];
  174. dst.at<uchar>(i,j) = (r+g+b)/3;
  175. }
  176. }
  177.  
  178. imshow("input image",src);
  179. imshow("gray image",dst);
  180. waitKey();
  181. }
  182. }
  183.  
  184. void testBGR2HSV()
  185. {
  186. char fname[MAX_PATH];
  187. while (openFileDlg(fname))
  188. {
  189. Mat src = imread(fname);
  190. int height = src.rows;
  191. int width = src.cols;
  192.  
  193. // Componentele d eculoare ale modelului HSV
  194. Mat H = Mat(height, width, CV_8UC1);
  195. Mat S = Mat(height, width, CV_8UC1);
  196. Mat V = Mat(height, width, CV_8UC1);
  197.  
  198. // definire pointeri la matricele (8 biti/pixeli) folosite la afisarea componentelor individuale H,S,V
  199. uchar* lpH = H.data;
  200. uchar* lpS = S.data;
  201. uchar* lpV = V.data;
  202.  
  203. Mat hsvImg;
  204. cvtColor(src, hsvImg, CV_BGR2HSV);
  205.  
  206. // definire pointer la matricea (24 biti/pixeli) a imaginii HSV
  207. uchar* hsvDataPtr = hsvImg.data;
  208.  
  209. for (int i = 0; i<height; i++)
  210. {
  211. for (int j = 0; j<width; j++)
  212. {
  213. int hi = i*width * 3 + j * 3;
  214. int gi = i*width + j;
  215.  
  216. lpH[gi] = hsvDataPtr[hi] * 510 / 360; // lpH = 0 .. 255
  217. lpS[gi] = hsvDataPtr[hi + 1]; // lpS = 0 .. 255
  218. lpV[gi] = hsvDataPtr[hi + 2]; // lpV = 0 .. 255
  219. }
  220. }
  221.  
  222. imshow("input image", src);
  223. imshow("H", H);
  224. imshow("S", S);
  225. imshow("V", V);
  226.  
  227. waitKey();
  228. }
  229. }
  230.  
  231. void testResize()
  232. {
  233. char fname[MAX_PATH];
  234. while(openFileDlg(fname))
  235. {
  236. Mat src;
  237. src = imread(fname);
  238. Mat dst1,dst2;
  239. //without interpolation
  240. resizeImg(src,dst1,320,false);
  241. //with interpolation
  242. resizeImg(src,dst2,320,true);
  243. imshow("input image",src);
  244. imshow("resized image (without interpolation)",dst1);
  245. imshow("resized image (with interpolation)",dst2);
  246. waitKey();
  247. }
  248. }
  249.  
  250. void testCanny()
  251. {
  252. char fname[MAX_PATH];
  253. while(openFileDlg(fname))
  254. {
  255. Mat src,dst,gauss;
  256. src = imread(fname,CV_LOAD_IMAGE_GRAYSCALE);
  257. double k = 0.4;
  258. int pH = 50;
  259. int pL = (int) k*pH;
  260. GaussianBlur(src, gauss, Size(5, 5), 0.8, 0.8);
  261. Canny(gauss,dst,pL,pH,3);
  262. imshow("input image",src);
  263. imshow("canny",dst);
  264. waitKey();
  265. }
  266. }
  267.  
  268. void testVideoSequence()
  269. {
  270. VideoCapture cap("Videos/rubic.avi"); // off-line video from file
  271. //VideoCapture cap(0); // live video from web cam
  272. if (!cap.isOpened()) {
  273. printf("Cannot open video capture device.\n");
  274. waitKey(0);
  275. return;
  276. }
  277.  
  278. Mat edges;
  279. Mat frame;
  280. char c;
  281.  
  282. while (cap.read(frame))
  283. {
  284. Mat grayFrame;
  285. cvtColor(frame, grayFrame, CV_BGR2GRAY);
  286. Canny(grayFrame,edges,40,100,3);
  287. imshow("source", frame);
  288. imshow("gray", grayFrame);
  289. imshow("edges", edges);
  290. c = cvWaitKey(0); // waits a key press to advance to the next frame
  291. if (c == 27) {
  292. // press ESC to exit
  293. printf("ESC pressed - capture finished\n");
  294. break; //ESC pressed
  295. };
  296. }
  297. }
  298.  
  299.  
  300. void testSnap()
  301. {
  302. VideoCapture cap(0); // open the deafult camera (i.e. the built in web cam)
  303. if (!cap.isOpened()) // openenig the video device failed
  304. {
  305. printf("Cannot open video capture device.\n");
  306. return;
  307. }
  308.  
  309. Mat frame;
  310. char numberStr[256];
  311. char fileName[256];
  312.  
  313. // video resolution
  314. Size capS = Size((int)cap.get(CV_CAP_PROP_FRAME_WIDTH),
  315. (int)cap.get(CV_CAP_PROP_FRAME_HEIGHT));
  316.  
  317. // Display window
  318. const char* WIN_SRC = "Src"; //window for the source frame
  319. namedWindow(WIN_SRC, CV_WINDOW_AUTOSIZE);
  320. cvMoveWindow(WIN_SRC, 0, 0);
  321.  
  322. const char* WIN_DST = "Snapped"; //window for showing the snapped frame
  323. namedWindow(WIN_DST, CV_WINDOW_AUTOSIZE);
  324. cvMoveWindow(WIN_DST, capS.width + 10, 0);
  325.  
  326. char c;
  327. int frameNum = -1;
  328. int frameCount = 0;
  329.  
  330. for (;;)
  331. {
  332. cap >> frame; // get a new frame from camera
  333. if (frame.empty())
  334. {
  335. printf("End of the video file\n");
  336. break;
  337. }
  338.  
  339. ++frameNum;
  340.  
  341. imshow(WIN_SRC, frame);
  342.  
  343. c = cvWaitKey(10); // waits a key press to advance to the next frame
  344. if (c == 27) {
  345. // press ESC to exit
  346. printf("ESC pressed - capture finished");
  347. break; //ESC pressed
  348. }
  349. if (c == 115){ //'s' pressed - snapp the image to a file
  350. frameCount++;
  351. fileName[0] = NULL;
  352. sprintf(numberStr, "%d", frameCount);
  353. strcat(fileName, "Images/A");
  354. strcat(fileName, numberStr);
  355. strcat(fileName, ".bmp");
  356. bool bSuccess = imwrite(fileName, frame);
  357. if (!bSuccess)
  358. {
  359. printf("Error writing the snapped image\n");
  360. }
  361. else
  362. imshow(WIN_DST, frame);
  363. }
  364. }
  365.  
  366. }
  367.  
  368. void MyCallBackFunc(int event, int x, int y, int flags, void* param)
  369. {
  370. Mat* src = (Mat*)param;
  371. if (event == CV_EVENT_LBUTTONDOWN)
  372. {
  373. Vec3b pixel = (*src).at<Vec3b>(y, x);
  374. Mat_<Vec3b> result = src->clone();
  375. /*Mat_<Vec3b> keeper(result.rows, result.cols);
  376.  
  377. for (int i = 0; i < result.rows; ++i) {
  378. for (int j = 0; j < result.cols; ++j) {
  379. keeper(i, j) = result(i, j);
  380. }
  381. }*/
  382.  
  383. Vec3b black;
  384. black[0] = 0;
  385. black[1] = 0;
  386. black[2] = 0;
  387.  
  388. Vec3b red;
  389. red[0] = 0;
  390. red[1] = 0;
  391. red[2] = 255;
  392.  
  393.  
  394. // AREA
  395. int area = 0;
  396. for (int i = 0; i < result.rows; ++i) {
  397. for (int j = 0; j < result.cols; ++j) {
  398. if (result(i, j)[0] == pixel[0] && result(i, j)[1] == pixel[1] && result(i, j)[2] == pixel[2]) {
  399. result(i, j) = black;
  400. area++;
  401. }
  402. }
  403. }
  404. imshow("My Area", result);
  405.  
  406. // CENTER OF MASS
  407. result = src->clone();
  408. int sumR = 0;
  409. int sumC = 0;
  410. for (int i = 0; i < result.rows; ++i) {
  411. for (int j = 0; j < result.cols; ++j) {
  412. if (result(i, j)[0] == pixel[0] && result(i, j)[1] == pixel[1] && result(i, j)[2] == pixel[2]) {
  413. sumR += i;
  414. sumC += j;
  415. }
  416. }
  417. }
  418. sumR /= area;
  419. sumC /= area;
  420. result(sumR, sumC) = black;
  421. result(sumR+1, sumC) = black;
  422. result(sumR+2, sumC) = black;
  423. result(sumR, sumC+1) = black;
  424. result(sumR, sumC+2) = black;
  425. result(sumR-1, sumC) = black;
  426. result(sumR-2, sumC) = black;
  427. result(sumR, sumC-1) = black;
  428. result(sumR, sumC-2) = black;
  429. imshow("My Center Of Mass", result);
  430.  
  431. // AXIS OF ELONG
  432.  
  433. result = src->clone();
  434. int S1 = 0, S2 = 0, S3 = 0;
  435. for (int i = 0; i < result.rows; ++i) {
  436. for (int j = 0; j < result.cols; ++j) {
  437. if (result(i, j)[0] == pixel[0] && result(i, j)[1] == pixel[1] && result(i, j)[2] == pixel[2]) {
  438. S1 += (i - sumR) * (j - sumC);
  439. S2 += pow((j - sumC), 2);
  440. S3 += pow((i - sumR), 2);
  441. }
  442. }
  443. }
  444. S1 *= 2;
  445. int S = S2 - S3;
  446. float phi = atan2(S1, S);
  447. phi /= 2;
  448.  
  449. Point2i pc;
  450. pc.y = sumR;
  451. pc.x = sumC;
  452. Point2i pd;
  453. pd.y = sumR + 100 * sin(phi);
  454. pd.x = sumC + 100 * cos(phi);
  455. line(result, pc, pd, black, 1);
  456. imshow("My axis", result);
  457.  
  458.  
  459. // PERIMETER
  460. result = src->clone();
  461. int perimeter = 0;
  462. int diffListX[] = { 0, 0, -1, 1, 1, -1, -1, 1};
  463. int diffListY[] = { -1, 1, 0, 0, -1, 1, -1, 1};
  464. for (int i = 0; i < result.rows; ++i) {
  465. for (int j = 0; j < result.cols; ++j) {
  466. if (result(i, j)[0] == pixel[0] && result(i, j)[1] == pixel[1] && result(i, j)[2] == pixel[2]) {
  467. boolean Ok = false;
  468. for (int k = 0; k < 8; ++k) {
  469. int a = i + diffListX[k];
  470. int b = j + diffListY[k];
  471. if (result(a, b)[0] == 255 && result(a, b)[1] == 255 && result(a, b)[2] == 255) {
  472. Ok = true;
  473. }
  474. }
  475. if (Ok) {
  476. result(i, j) = black;
  477. perimeter++;
  478. }
  479. }
  480. }
  481. }
  482.  
  483. imshow("My Perimeter", result);
  484.  
  485. // THINNES
  486. float T = 4 * 3.14;
  487. T *= area;
  488. int Pat2 = pow(perimeter, 2);
  489. T /= Pat2;
  490.  
  491. // ASPECT RATIO
  492. result = src->clone();
  493. float R;
  494. int minC = result.cols, minR = result.rows, maxC = 0, maxR = 0;
  495. for (int i = 0; i < result.rows; ++i) {
  496. for (int j = 0; j < result.cols; ++j) {
  497. if (result(i, j)[0] == pixel[0] && result(i, j)[1] == pixel[1] && result(i, j)[2] == pixel[2]) {
  498. if (minC > j) {
  499. minC = j;
  500. }
  501. if (minR > i) {
  502. minR = i;
  503. }
  504. if (maxC < j) {
  505. maxC = j;
  506. }
  507. if (maxR < i) {
  508. maxR = i;
  509. }
  510. }
  511. }
  512. }
  513. R =(float) (maxC - minC + 1) / (maxR - minR + 1);
  514.  
  515. std::cout << R << '\n';
  516.  
  517. Point2i p1;
  518. p1.y = minR;
  519. p1.x = minC;
  520. Point2i p2;
  521. p2.y = maxR;
  522. p2.x = minC;
  523. Point2i p3;
  524. p3.y = maxR;
  525. p3.x = maxC;
  526. Point2i p4;
  527. p4.y = minR;
  528. p4.x = maxC;
  529.  
  530. line(result, p1, p2, black, 1);
  531. line(result, p2, p3, black, 1);
  532. line(result, p1, p4, black, 1);
  533. line(result, p3, p4, black, 1);
  534. imshow("My Aspect Ratio", result);
  535.  
  536. // PROJECTIONS
  537. result = src->clone();
  538. for (int i = 0; i < result.rows; ++i) {
  539. int counter = 0;
  540. for (int j = 0; j < result.cols; ++j) {
  541. if (result(i, j)[0] == pixel[0] && result(i, j)[1] == pixel[1] && result(i, j)[2] == pixel[2]) {
  542. counter++;
  543. }
  544. }
  545. Point2i p1;
  546. p1.y = i;
  547. p1.x = result.cols;
  548. Point2i p2;
  549. p2.y = i;
  550. p2.x = result.cols - counter;
  551. line(result, p1, p2, black, 1);
  552. }
  553. for (int i = 0; i < result.cols; ++i) {
  554. int counter = 0;
  555. for (int j = 0; j < result.rows; ++j) {
  556. if (result(j, i)[0] == pixel[0] && result(j, i)[1] == pixel[1] && result(j, i)[2] == pixel[2]) {
  557. counter++;
  558. }
  559. }
  560. Point2i p1;
  561. p1.y = result.rows;
  562. p1.x = i;
  563. Point2i p2;
  564. p2.y = result.rows - counter;
  565. p2.x = i;
  566. line(result, p1, p2, black, 1);
  567. }
  568.  
  569. imshow("My ", result);
  570.  
  571. }
  572. }
  573.  
  574. void testMouseClick()
  575. {
  576. Mat_<Vec3b> src;
  577. // Read image from file
  578. char fname[MAX_PATH];
  579. while (openFileDlg(fname))
  580. {
  581. src = imread(fname, CV_LOAD_IMAGE_COLOR);
  582. namedWindow("My Window", 1);
  583. imshow("My Window", src);
  584. setMouseCallback("My Window", MyCallBackFunc, &src);
  585. waitKey(0);
  586. }
  587. }
  588.  
  589. /* Histogram display function - display a histogram using bars (simlilar to L3 / PI)
  590. Input:
  591. name - destination (output) window name
  592. hist - pointer to the vector containing the histogram values
  593. hist_cols - no. of bins (elements) in the histogram = histogram image width
  594. hist_height - height of the histogram image
  595. Call example:
  596. showHistogram ("MyHist", hist_dir, 255, 200);
  597. */
  598. void showHistogram(const std::string& name, int* hist, const int hist_cols, const int hist_height)
  599. {
  600. Mat imgHist(hist_height, hist_cols, CV_8UC3, CV_RGB(255, 255, 255)); // constructs a white image
  601.  
  602. //computes histogram maximum
  603. int max_hist = 0;
  604. for (int i = 0; i<hist_cols; i++)
  605. if (hist[i] > max_hist)
  606. max_hist = hist[i];
  607. double scale = 1.0;
  608. scale = (double)hist_height / max_hist;
  609. int baseline = hist_height - 1;
  610.  
  611. for (int x = 0; x < hist_cols; x++) {
  612. Point p1 = Point(x, baseline);
  613. Point p2 = Point(x, baseline - cvRound(hist[x] * scale));
  614. line(imgHist, p1, p2, CV_RGB(255, 0, 255)); // histogram bins colored in magenta
  615. }
  616.  
  617. imshow(name, imgHist);
  618. }
  619.  
  620. void copyRGBs() {
  621. Mat_<Vec3b> img = imread("Images/flowers_24bits.bmp", CV_LOAD_IMAGE_COLOR);
  622. Mat_<uchar> imgR(img.rows, img.cols);
  623. Mat_<uchar> imgG(img.rows, img.cols);
  624. Mat_<uchar> imgB(img.rows, img.cols);
  625.  
  626. for (int i = 0; i < img.rows; ++i) {
  627. for (int j = 0; j < img.cols; ++j) {
  628. imgR(i, j) = img(i, j)[2];
  629. imgG(i, j) = img(i, j)[1];
  630. imgB(i, j) = img(i, j)[0];
  631. }
  632. }
  633.  
  634. imshow("Red image", imgR);
  635. imshow("Green image", imgG);
  636. imshow("Blue image", imgB);
  637. waitKey(0);
  638. }
  639.  
  640. void fromColorToRGB() {
  641. Mat_<Vec3b> img = imread("Images/kids.bmp", CV_LOAD_IMAGE_COLOR);
  642. Mat_<uchar> result(img.rows, img.cols);
  643.  
  644. for (int i = 0; i < img.rows; ++i) {
  645. for (int j = 0; j < img.cols; ++j) {
  646. result(i, j) = (img(i, j)[0] + img(i, j)[1] + img(i, j)[2]) / 3;
  647. }
  648. }
  649.  
  650. imshow("Gray image", result);
  651.  
  652.  
  653. Mat_<uchar> resultCVT(img.rows, img.cols);
  654. cvtColor(img, resultCVT, CV_RGB2GRAY);
  655. imshow("CVT", resultCVT);
  656. waitKey(0);
  657. }
  658.  
  659. void convertBlackAndWhite(int t) {
  660. Mat_<uchar> img = imread("Images/eight.bmp", CV_LOAD_IMAGE_GRAYSCALE);
  661. Mat_<uchar> result(img.rows, img.cols);
  662.  
  663. for (int i = 0; i < img.rows; ++i) {
  664. for (int j = 0; j < img.cols; ++j) {
  665. int aux = img(i, j);
  666. if (aux < t) {
  667. result(i, j) = 0;
  668. }
  669. else {
  670. result(i, j) = 255;
  671. }
  672. }
  673. }
  674. imshow("B&W image", result);
  675. waitKey(0);
  676. }
  677.  
  678. void computeHSV() {
  679. Mat_<Vec3b> img = imread("Images/Lena_24bits.bmp", CV_LOAD_IMAGE_COLOR);
  680. Mat_<uchar> auxH(img.rows, img.cols);
  681. Mat_<uchar> auxS(img.rows, img.cols);
  682. Mat_<uchar> auxV(img.rows, img.cols);
  683.  
  684. for (int i = 0; i < img.rows; ++i) {
  685. for (int j = 0; j < img.cols; ++j) {
  686. float r = (float) img(i, j)[2] / 255;
  687. float g = (float) img(i, j)[1] / 255;
  688. float b = (float) img(i, j)[0] / 255;
  689.  
  690. float M = max(max(r, g), b);
  691. float m = min(min(r, g), b);
  692. float C = M - m;
  693.  
  694. float V = M;
  695.  
  696. float S;
  697. if(V != 0)
  698. S = C / V;
  699. else // grayscale
  700. S = 0;
  701.  
  702. float H;
  703. if(C != 0) {
  704. if (M == r) H = 60 * (g - b) / C;
  705. if (M == g) H = 120 + 60 * (b - r) / C;
  706. if (M == b) H = 240 + 60 * (r - g) / C;
  707. }
  708. else // grayscale
  709. H = 0;
  710.  
  711. if(H < 0)
  712. H = H + 360;
  713.  
  714. H = H * 255 / 360;
  715. S = S * 255;
  716. V = V * 255;
  717.  
  718. auxH(i, j) = H;
  719. auxS(i, j) = S;
  720. auxV(i, j) = V;
  721. }
  722. }
  723.  
  724.  
  725. imshow("H", auxH);
  726. imshow("S", auxS);
  727. imshow("V", auxV);
  728. waitKey(0);
  729.  
  730.  
  731. }
  732.  
  733. bool isInside(Mat img, int i, int j) {
  734. if (i >= img.rows) return false;
  735. if (j >= img.cols) return false;
  736. if (i < 0) return false;
  737. if (j < 0) return false;
  738. return true;
  739. }
  740.  
  741. bool isInside(Mat_<uchar> img, int i, int j) {
  742. if (i >= img.rows) return false;
  743. if (j >= img.cols) return false;
  744. if (i < 0) return false;
  745. if (j < 0) return false;
  746. return true;
  747. }
  748.  
  749. void calcHistogram(Mat_<uchar> img, int * hist, float * pdf, int m) {
  750. float M = (float)img.rows * img.cols;
  751. int bins = 256 / m;
  752.  
  753. for (int i = 0; i < 256; ++i)
  754. hist[i] = 0;
  755.  
  756. for (int i = 0; i < img.rows; ++i) {
  757. for (int j = 0; j < img.cols; ++j) {
  758. hist[img(i, j) / bins]++;
  759. }
  760. }
  761.  
  762. for (int i = 0; i < 256; ++i) {
  763. float aux = (float)hist[i];
  764. //printf("%f/n", aux);
  765. pdf[i] = aux / M;
  766. //printf("%f", pdf[i]);
  767. }
  768. }
  769.  
  770. void multilevelThresholding(int * hist, float * pdf, Mat_<uchar> image, Mat_<uchar> resultImage) {
  771. int WH = 5;
  772. int windowWidth = 2 * WH + 1;
  773. float TH = 0.0003;
  774. v.push_back(0);
  775.  
  776. float average;
  777. for (int k = WH; k <= 255 - WH; ++k) {
  778. float sum = 0;
  779. for (int j = k - WH; j <= k + WH; ++j) {
  780. sum += pdf[j];
  781. }
  782. average = (float)sum / windowWidth;
  783.  
  784. printf("AVG\n");
  785.  
  786. bool isHigher = true;
  787. for (int j = k - WH; j <= k + WH; ++j) {
  788. if (pdf[k] < pdf[j]) {
  789. isHigher = false;
  790. }
  791. }
  792. if (isHigher) {
  793. printf("IS HIGHER\n\n\n");
  794. }
  795.  
  796. if (pdf[k] > average + TH && isHigher) {
  797. v.push_back(k);
  798. printf("Pushback\n");
  799. }
  800. }
  801. v.push_back(255);
  802.  
  803.  
  804. for (int i = 0; i < image.rows; ++i) {
  805. for (int j = 0; j < image.cols; ++j) {
  806. //resultImage(i, j) = closestFromVector(image(i, j), v);
  807. int closest = v[0];
  808. for (auto const& it : v) {
  809. int currDifference = abs(closest - image(i, j));
  810. int newDifference = abs(it - image(i, j));
  811.  
  812. if (newDifference < currDifference)
  813. closest = it;
  814. }
  815. resultImage(i, j) = closest;
  816. }
  817. }
  818. }
  819.  
  820. void fsDithering(Mat_<uchar> source) {
  821. for (int i = 0; i < source.rows; ++i) {
  822. for (int j = 0; j < source.cols; ++j) {
  823. uchar oldPixel = source(i, j);
  824. int closest = v[0];
  825. for (auto const& it : v) {
  826. int currDifference = abs(closest - source(i, j));
  827. int newDifference = abs(it - source(i, j));
  828.  
  829. if (newDifference < currDifference)
  830. closest = it;
  831. }
  832. uchar newPixel = closest;
  833. source(i, j) = newPixel;
  834. uchar error = oldPixel - newPixel;
  835. if (j + 1 < source.cols)
  836. source(i, j + 1) = source(i, j + 1) + (7 * error / 16);
  837. if (i + 1 < source.rows && j - 1 < 0)
  838. source(j - 1, i + 1) = source(j - 1, i + 1) + (3 * error / 16);
  839. if (i + 1 < source.rows)
  840. source(i + 1, j) = source(i + 1, j) + (5 * error / 16);
  841. if (i + 1 < source.rows && j + 1 < source.cols)
  842. source(j + 1, i + 1) = source(j + 1, i + 1) + (error / 16);
  843. }
  844. }
  845.  
  846. imshow("FSD", source);
  847. waitKey(0);
  848.  
  849. }
  850.  
  851. Mat_<int> labelComponents(Mat_<uchar> src) {
  852. int diffListX[] = { 0, -1, 0, 1, -1, 1, -1, 1 };
  853. int diffListY[] = { -1, 0, 1, 0, -1, 1, 1, -1 };
  854. Mat_<int> toReturn(src.rows, src.cols);
  855. int label = 0;
  856.  
  857. for (int i = 0; i < src.rows; ++i) {
  858. for (int j = 0; j < src.cols; ++j) {
  859. toReturn(i, j) = 0;
  860. }
  861. }
  862.  
  863. for (int i = 0; i < src.rows; ++i) {
  864. for (int j = 0; j < src.cols; ++j) {
  865. if (src(i, j) == 0 && toReturn(i, j) == 0) {
  866. label++;
  867. toReturn(i, j) = label;
  868. Q = std::queue<Point2i>();
  869. Q.push({ i, j });
  870. while (!Q.empty()) {
  871. Point2i q = Q.front();
  872. Q.pop();
  873. for (int k = 0; k < 4; ++k) {
  874. int newX = q.x + diffListX[k];
  875. int newY = q.y + diffListY[k];
  876. if (newX >= 0 && newX < src.rows && newY >= 0 && newY < src.cols) {
  877. if (src(newX, newY) == 0 && toReturn(newX, newY) == 0) {
  878. toReturn(newX, newY) = label;
  879. Q.push({ newX, newY });
  880. }
  881. }
  882. }
  883. }
  884. }
  885. }
  886. }
  887. printf("%d", label);
  888. return toReturn;
  889. }
  890.  
  891. Mat_<Vec3b> colorLabels(Mat_<int> src) {
  892. Mat_<Vec3b> toReturn(src.rows, src.cols);
  893.  
  894. int maxLabel = -1;
  895. for (int i = 0; i < src.rows; ++i) {
  896. for (int j = 0; j < src.cols; ++j) {
  897. if (maxLabel < src(i, j)) {
  898. maxLabel = src(i, j);
  899. }
  900.  
  901. toReturn(i, j)[0] = 255;
  902. toReturn(i, j)[1] = 255;
  903. toReturn(i, j)[2] = 255;
  904.  
  905. }
  906. }
  907.  
  908. Vec3b * colors = new Vec3b[maxLabel + 1];
  909. for (int i = 1; i <= maxLabel; ++i) {
  910. colors[i][0] = d(gen);
  911. colors[i][1] = d(gen);
  912. colors[i][1] = d(gen);
  913. }
  914.  
  915.  
  916. for (int i = 0; i < src.rows; ++i) {
  917. for (int j = 0; j < src.cols; ++j) {
  918. if (src(i, j)) {
  919. toReturn(i, j) = colors[src(i, j)];
  920. }
  921. }
  922. }
  923.  
  924. free(colors);
  925.  
  926. return toReturn;
  927. }
  928.  
  929. void lab4() {
  930. Mat_<uchar> src;
  931. char fname[MAX_PATH];
  932. while (openFileDlg(fname))
  933. {
  934. src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
  935. namedWindow("My Window", 1);
  936. setMouseCallback("My Window", MyCallBackFunc, &src);
  937. imshow("My Window", src);
  938.  
  939. Mat_<int> matWithComp = labelComponents(src);
  940. //imshow("Connected", matWithComp);
  941.  
  942. Mat_<Vec3b> coloredImage = colorLabels(matWithComp);
  943. imshow("It's Complicated", coloredImage);
  944.  
  945.  
  946. waitKey(0);
  947. }
  948. }
  949.  
  950. int getMinimum(std::vector<int> src) {
  951. int mini = -1;
  952. for (auto const& it : src) {
  953. if (it > mini)
  954. mini = it;
  955. }
  956. return mini;
  957. }
  958.  
  959. Mat_<int> twoPass(Mat_<uchar> src) {
  960. int label = 0;
  961. Mat_<int> labels(src.rows, src.cols);
  962. int diffListX[] = { 0, -1, -1, -1 };
  963. int diffListY[] = { -1, -1, 0, 1 };
  964. /*for (int i = 0; i < src.rows; ++i) {
  965. for (int j = 0; j < src.cols; ++j) {
  966.  
  967. }
  968. }*/
  969.  
  970. labels.setTo(0);
  971.  
  972. std::vector<std::vector<int>> edges(99999);
  973.  
  974. for (int i = 0; i < src.rows; ++i) {
  975. for (int j = 0; j < src.cols; ++j) {
  976. if (src(i, j) == 0 && labels(i, j) == 0) {
  977. std::vector<int> L;
  978.  
  979. for (int k = 0; k < 4; ++k) {
  980. int newI = i + diffListX[k];
  981. int newJ = j + diffListY[k];
  982.  
  983. if (!(newI < 0 || newI >= src.rows || newJ < 0 || newJ >= src.cols)) {
  984. if (labels(newI, newJ) > 0) {
  985. L.push_back(labels(newI, newJ));
  986. }
  987. }
  988. }
  989.  
  990. if (L.size() == 0) {
  991. label++;
  992. labels(i, j) = label;
  993. }
  994. else {
  995. int x = getMinimum(L);
  996. labels(i, j) = x;
  997. for (auto const& it : L) {
  998. if (x != it) {
  999. edges.resize(label + 2);
  1000. edges[x].push_back(it);
  1001. edges[it].push_back(x);
  1002. }
  1003. }
  1004. }
  1005. }
  1006. }
  1007. }
  1008.  
  1009. int newLabel = 0;
  1010. int * newLabels = new int[label + 2];
  1011. for (int i = 0; i < label + 2; ++i) {
  1012. newLabels[i] = 0;
  1013. }
  1014.  
  1015. for (int i = 1; i <= label; ++i) {
  1016. if (newLabels[i] == 0) {
  1017. newLabel++;
  1018. QU = std::queue<int>();
  1019. newLabels[i] = newLabel;
  1020. QU.push(i);
  1021. while (!QU.empty()) {
  1022. int x = QU.front();
  1023. QU.pop();
  1024. for (auto const& it : edges[x]) {
  1025. if (newLabels[it] == 0) {
  1026. newLabels[it] = newLabel;
  1027. QU.push(it);
  1028. }
  1029. }
  1030. }
  1031. }
  1032. }
  1033.  
  1034. for (int i = 0; i < src.rows; i++) {
  1035. for (int j = 0; j < src.cols; ++j) {
  1036. labels(i, j) = newLabels[labels(i, j)];
  1037. }
  1038. }
  1039.  
  1040. return labels;
  1041. }
  1042.  
  1043. void lab4twoPass() {
  1044. Mat_<uchar> src;
  1045. char fname[MAX_PATH];
  1046. while (openFileDlg(fname))
  1047. {
  1048. src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
  1049. namedWindow("My Window", 1);
  1050. setMouseCallback("My Window", MyCallBackFunc, &src);
  1051. imshow("My Window", src);
  1052.  
  1053.  
  1054. Mat_<int> matWithComp = twoPass(src);
  1055. //imshow("Connected", matWithComp);
  1056.  
  1057. Mat_<Vec3b> coloredImage = colorLabels(matWithComp);
  1058. imshow("It's Complicated", coloredImage);
  1059. waitKey(0);
  1060. }
  1061. }
  1062.  
  1063. void drawWithChainCode() {
  1064.  
  1065. std::ifstream myReadFile;
  1066. myReadFile.open("Images/reconstruct.txt");
  1067. int di[] = { 0, -1, -1, -1, 0, 1, 1, 1 };
  1068. int dj[] = { 1, 1, 0, -1, -1, -1, 0, 1 };
  1069.  
  1070. Mat_<uchar> result(1500, 1500);
  1071.  
  1072. int startI, startJ, nr;
  1073. if (myReadFile.is_open()) {
  1074. myReadFile >> startI >> startJ >> nr;
  1075. int x;
  1076. for (int i = 0; i < nr; ++i) {
  1077. myReadFile >> x;
  1078. startI += di[x];
  1079. startJ += dj[x];
  1080. result(startI, startJ) = 0;
  1081. }
  1082. }
  1083. myReadFile.close();
  1084.  
  1085. imshow("RECREATA", result);
  1086. waitKey(0);
  1087. /*for (int i = 0; i < result.rows; ++i) {
  1088. for (int j = 0; j < result.cols; ++j) {
  1089. result(i, j) = 255;
  1090. }
  1091. }
  1092.  
  1093. result(startI, startJ) = 0;
  1094. for (int x : chain) {
  1095. startI += di[x];
  1096. startJ += dj[x];
  1097. result(startI, startJ) = 0;
  1098. }
  1099.  
  1100. imshow("RECREATA", result);
  1101. waitKey(0);*/
  1102. }
  1103.  
  1104. void borderTrace() {
  1105. Mat_<uchar> src;
  1106. // Read image from file
  1107. char fname[MAX_PATH];
  1108. while (openFileDlg(fname))
  1109. {
  1110. src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
  1111. namedWindow("My Window", 1);
  1112. imshow("My Window", src);
  1113.  
  1114. int di[] = { 0, -1, -1, -1, 0, 1, 1, 1 };
  1115. int dj[] = { 1, 1, 0, -1, -1, -1, 0, 1 };
  1116.  
  1117. Mat_<uchar> result = src.clone();
  1118. uchar background = result(0, 0);
  1119. uchar color;
  1120. std::vector<std::pair<int, int>> p;
  1121. std::vector<int> c;
  1122. int coordI, coordJ;
  1123.  
  1124. for (int i = 0; i < result.rows; ++i) {
  1125. for (int j = 0; j < result.cols; ++j) {
  1126. if (result(i, j) != background) {
  1127. color = result(i, j);
  1128. coordI = i;
  1129. coordJ = j;
  1130. goto next;
  1131. }
  1132. }
  1133. }
  1134.  
  1135. next:
  1136. int dir = 7;
  1137. p.push_back(std::make_pair(coordI, coordJ));
  1138. bool run = true;
  1139. while (run) {
  1140. if (dir % 2 == 0) {
  1141. dir = (dir + 7) % 8;
  1142. }
  1143. else {
  1144. dir = (dir + 6) % 8;
  1145. }
  1146.  
  1147.  
  1148. for (int k = 0; k < 8; ++k) {
  1149. if (result(coordI + di[(dir + k) % 8], coordJ + dj[(dir + k) % 8]) == color) {
  1150. p.push_back(std::make_pair(coordI + di[(dir + k) % 8], coordJ + dj[(dir + k) % 8]));
  1151. coordI = coordI + di[(dir + k) % 8];
  1152. coordJ = coordJ + dj[(dir + k) % 8];
  1153. dir = (dir + k) % 8;
  1154. c.push_back(dir);
  1155. std::cout << dir << '\n';
  1156. break;
  1157. }
  1158. }
  1159. int size = (int) p.size();
  1160. 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) {
  1161. run = false;
  1162. }
  1163. }
  1164.  
  1165. Mat_<uchar> toShow(src.rows, src.cols);
  1166. for (int i = 0; i < result.rows; ++i) {
  1167. for (int j = 0; j < result.cols; ++j) {
  1168. toShow(i, j) = 255;
  1169. }
  1170. }
  1171.  
  1172. for (std::pair<int, int> pairr : p) {
  1173. toShow(pairr.first, pairr.second) = 0;
  1174. }
  1175.  
  1176. std::vector<int> der;
  1177. der.push_back((c.back() - c.front()) % 8);
  1178. for (int z = 1; z < c.size(); ++z) {
  1179. int result = (c.at(z) - c.at(z - 1)) % 8;
  1180. if (result < 0) {
  1181. der.push_back(result + 8);
  1182. }
  1183. else {
  1184. der.push_back(result);
  1185. }
  1186. }
  1187.  
  1188. for (int z : der) {
  1189. std::cout << z << ' ';
  1190. }
  1191. imshow("RESULT", toShow);
  1192.  
  1193. waitKey(0);
  1194. }
  1195. }
  1196.  
  1197. void dilatate() {
  1198. Mat_<uchar> input = imread("Images/Morphological_Op_Images/1_Dilate/reg1neg1_bw.bmp", CV_LOAD_IMAGE_GRAYSCALE);
  1199. Mat_<uchar> result = input.clone();
  1200. uchar background = input(0, 0);
  1201.  
  1202. for (int i = 0; i < input.rows; ++i) {
  1203. for (int j = 0; j < input.cols; ++j) {
  1204. if (input(i, j) != background) {
  1205. if(i+1 < input.rows)
  1206. result(i+1, j) = input(i, j);
  1207. if (i + 1 < input.rows && j + 1 < input.cols)
  1208. result(i+1, j+1) = input(i, j);
  1209. if(j + 1 < input.cols)
  1210. result(i, j+1) = input(i, j);
  1211. if (i - 1 >= 0 && j + 1 < input.cols)
  1212. result(i-1, j+1) = input(i, j);
  1213. if (i - 1 >= 0)
  1214. result(i-1, j) = input(i, j);
  1215. if (i - 1 >= 0 && j - 1 >= 0)
  1216. result(i-1, j-1) = input(i, j);
  1217. if(j - 1 >= 0)
  1218. result(i, j-1) = input(i, j);
  1219. if (i + 1 < input.rows && j - 1 >= 0)
  1220. result(i+1, j-1) = input(i, j);
  1221. }
  1222. }
  1223. }
  1224.  
  1225. imshow("INPUT", input);
  1226. imshow("RESULT", result);
  1227.  
  1228. waitKey(0);
  1229. }
  1230.  
  1231. void calcHistogram(Mat_<uchar> img, int * hist) {
  1232. float M = (float)img.rows * img.cols;
  1233.  
  1234. for (int i = 0; i < 256; ++i)
  1235. hist[i] = 0;
  1236.  
  1237. for (int i = 0; i < img.rows; ++i) {
  1238. for (int j = 0; j < img.cols; ++j) {
  1239. hist[img(i, j)]++;
  1240. }
  1241. }
  1242. }
  1243.  
  1244. float meanValue(int* hist, float area) {
  1245. int toReturn = 0;
  1246. for (int i = 0; i < 256; ++i) {
  1247. toReturn += i * hist[i];
  1248. }
  1249. return (float) toReturn / area;
  1250. }
  1251.  
  1252. float stdDerivation(int* hist, float meanValue, int dim) {
  1253. double toReturn = 0;
  1254. for (int i = 0; i < 256; ++i) {
  1255. toReturn += pow((i - meanValue), 2) * hist[i];
  1256. }
  1257. std::cout << "Standard " << toReturn << '\n';
  1258. float sq = sqrt((float)toReturn/dim);
  1259. return sq;
  1260. }
  1261.  
  1262. int maxIntensity(int * hist) {
  1263. for (int i = 255; i >= 0; ++i) {
  1264. if (hist[i] != 0) {
  1265. return i;
  1266. }
  1267. }
  1268. return 0;
  1269. }
  1270.  
  1271. int minIntensity(int * hist) {
  1272. for (int i = 0; i < 256; ++i) {
  1273. if (hist[i] != 0) {
  1274. return i;
  1275. }
  1276. }
  1277. return 255;
  1278. }
  1279.  
  1280.  
  1281. void strechHist(int * hist, int* toReturn, int gMin, int gMax) {
  1282. int minG = minIntensity(hist);
  1283. int maxG = maxIntensity(hist);
  1284.  
  1285. toReturn = new int[256];
  1286.  
  1287. for (int i = 0; i < 256; ++i) {
  1288. toReturn[i] = gMin + (hist[i] - minG) * (gMax - gMin) / (maxG - minG);
  1289. }
  1290. }
  1291.  
  1292. void gammaHist(int * hist, int* toReturn, int gMin, int gMax) {
  1293.  
  1294. }
  1295.  
  1296. void lab8() {
  1297. Mat_<uchar> src;
  1298. // Read image from file
  1299. char fname[MAX_PATH];
  1300. while (openFileDlg(fname))
  1301. {
  1302. src = imread(fname, 0);
  1303. imshow("Source Window", src);
  1304. int * hist = new int[256];
  1305.  
  1306. calcHistogram(src, hist);
  1307.  
  1308. showHistogram("Mein Hist", hist, 256, 256);
  1309.  
  1310. float mv = meanValue(hist, src.rows * src.cols);
  1311. float sd = stdDerivation(hist, mv, src.rows * src.cols);
  1312.  
  1313. int mnIntensity = minIntensity(hist);
  1314. int mxIntensity = maxIntensity(hist);
  1315.  
  1316. std::cout << "Mean value " << mv << '\n';
  1317. std::cout << "Standard derivation " << sd << '\n';
  1318. std::cout << "Min Intensity " << mnIntensity << '\n';
  1319. std::cout << "Max Intensity " << mxIntensity << '\n';
  1320.  
  1321. int T = 156;
  1322. int Tf;
  1323. int error = 1;
  1324.  
  1325. do {
  1326. int N1 = 0;
  1327. for (int i = mnIntensity; i < T+1; ++i) {
  1328. N1 += hist[i];
  1329. }
  1330.  
  1331. int N2 = 0;
  1332. for (int i = T + 1; i < mxIntensity; ++i) {
  1333. N2 += hist[i];
  1334. }
  1335.  
  1336. int G1 = 0;
  1337. for (int i = mnIntensity; i < T+1; ++i) {
  1338. G1 += hist[i] * i;
  1339. }
  1340.  
  1341. int G2 = 0;
  1342. for (int i = T + 1; i < mxIntensity; ++i) {
  1343. G2 += hist[i] * i;
  1344. }
  1345.  
  1346. G1 /= N1;
  1347. G2 /= N2;
  1348.  
  1349. Tf = T;
  1350. T = (G1 + G2) / 2;
  1351.  
  1352. } while (abs(T - Tf) > error);
  1353.  
  1354.  
  1355. std::cout << "DDDDDDD " << T << '\n';
  1356.  
  1357. Mat_<uchar> result(src.rows, src.cols);
  1358. for (int i = 0; i < src.rows; ++i) {
  1359. for (int j = 0; j < src.cols; ++j) {
  1360. if (src(i, j) < T) {
  1361. result(i, j) = 0;
  1362. }
  1363. else {
  1364. result(i, j) = 255;
  1365. }
  1366. }
  1367. }
  1368.  
  1369. imshow("THR", result);
  1370.  
  1371. int* strech = new int[256];
  1372. strechHist(hist, strech, 100, 200);
  1373.  
  1374. showHistogram("Mein Hist2", strech, 256, 256);
  1375.  
  1376.  
  1377. waitKey(0);
  1378. }
  1379.  
  1380. }
  1381.  
  1382. Mat_<float> convolute(Mat_<uchar> source, Mat_<float> h) {
  1383. Mat_<float> toReturn(source.rows, source.cols);
  1384. int k = (h.rows - 1) / 2;
  1385.  
  1386. for (int i = 0; i < source.rows; ++i) {
  1387. for (int j = 0; j < source.cols; ++j) {
  1388. float sum = 0;
  1389.  
  1390. /*for (int l = i - k; l < i + k; ++l) {
  1391. for (int m = j - k; m < j + k; ++m) {
  1392. if (isInside(source, l, m)) {
  1393. sum += source(l, m) * h(i)
  1394. }
  1395. }
  1396. }*/
  1397.  
  1398. for (int l = 0; l < h.rows; ++l) {
  1399. for (int m = 0; m < h.cols; ++m) {
  1400. if (isInside(source, i + l - k, j + m - k)) {
  1401. sum += (float)(h(l, m) * source(i + l - k, j + m - k));
  1402. }
  1403. }
  1404. }
  1405.  
  1406. toReturn(i, j) = sum;
  1407. }
  1408. }
  1409.  
  1410. return toReturn;
  1411. }
  1412.  
  1413. Mat_<uchar> normalizeMat(Mat_<float> toNormalize, float minimul, float maximul) {
  1414. Mat_<uchar> toReturn(toNormalize.rows, toNormalize.cols);
  1415. for (int i = 0; i < toNormalize.rows; ++i) {
  1416. for (int j = 0; j < toNormalize.cols; ++j) {
  1417. toReturn(i, j) = ((toNormalize(i, j) - minimul) * 255) / (maximul - minimul);
  1418. }
  1419. }
  1420. return toReturn;
  1421. }
  1422.  
  1423. float getMaxValue(Mat_<float> h) {
  1424. float toReturn = 0;
  1425. for (int i = 0; i < h.rows; ++i) {
  1426. for (int j = 0; j < h.cols; ++j) {
  1427. if (h(i, j) > 0) {
  1428. toReturn += h(i, j);
  1429. }
  1430. }
  1431. }
  1432. return (toReturn * 255);
  1433. }
  1434.  
  1435. float getMinValue(Mat_<float> h) {
  1436. float toReturn = 0;
  1437. for (int i = 0; i < h.rows; ++i) {
  1438. for (int j = 0; j < h.cols; ++j) {
  1439. if (h(i, j) < 0) {
  1440. toReturn += h(i, j);
  1441. }
  1442. }
  1443. }
  1444. return (toReturn * 255);
  1445. }
  1446.  
  1447. void lab9() {
  1448. Mat_<uchar> src;
  1449. // Read image from file
  1450. char fname[MAX_PATH];
  1451. while (openFileDlg(fname))
  1452. {
  1453. src = imread(fname, 0);
  1454. Mat_<float> h(3, 3);
  1455. for (int i = 0; i < h.rows; ++i) {
  1456. for (int j = 0; j < h.cols; ++j) {
  1457. h(i, j) = (float)-1;
  1458. }
  1459. }
  1460. h(1, 1) = 8;
  1461. Mat_<float> convoluted(src.rows, src.cols);
  1462. convoluted = convolute(src, h);
  1463. imshow("Conv", convoluted);
  1464. Mat_<uchar> result(convoluted.rows, convoluted.cols);
  1465. int a = getMinValue(h);
  1466. a *= -1;
  1467. int b = getMaxValue(h);
  1468. result = normalizeMat(convoluted, 0, max(a,b));
  1469. imshow("Res", result);
  1470. waitKey(0);
  1471. }
  1472. }
  1473.  
  1474. void centering_transform(Mat img) {
  1475. //expects floating point image
  1476. for (int i = 0; i < img.rows; i++) {
  1477. for (int j = 0; j < img.cols; j++) {
  1478. img.at<float>(i, j) = ((i + j) & 1) ? -img.at<float>(i, j) : img.at<float>(i, j);
  1479. }
  1480. }
  1481. }
  1482.  
  1483.  
  1484. Mat generic_frequency_domain_filter(Mat src) {
  1485. //convert input image to float image
  1486. Mat srcf;
  1487. src.convertTo(srcf, CV_32FC1);
  1488. //centering transformation
  1489. centering_transform(srcf);
  1490. //perform forward transform with complex image output
  1491.  
  1492.  
  1493. Mat fourier;
  1494. dft(srcf, fourier, DFT_COMPLEX_OUTPUT);
  1495. //split into real and imaginary channels
  1496. Mat channels[] = { Mat::zeros(src.size(), CV_32F), Mat::zeros(src.size(), CV_32F) };
  1497. split(fourier, channels); // channels[0] = Re(DFT(I)), channels[1] = Im(DFT(I))
  1498. //calculate magnitude and phase in floating point images mag and phi
  1499. Mat mag, phi;
  1500. magnitude(channels[0], channels[1], mag);
  1501. phase(channels[0], channels[1], phi);
  1502.  
  1503.  
  1504.  
  1505.  
  1506.  
  1507. //display the phase and magnitude images here
  1508. imshow("MAG", mag);
  1509. imshow("PHS", phi);
  1510. //insert filtering operations on Fourier coefficients here
  1511. int centerI = src.rows / 2;
  1512. int centerJ = src.cols / 2;
  1513. /*for (int i = 0; i < src.rows; ++i) {
  1514. for (int j = 0; j < src.cols; ++j) {
  1515. if (sqrt(pow((centerI - i), 2) + pow((centerJ - j), 2)) >= 20)
  1516. mag.at<float>(i, j) = 0.f;
  1517. }
  1518. }*/
  1519.  
  1520. for (int i = 0; i < src.rows; ++i) {
  1521. for (int j = 0; j < src.cols; ++j) {
  1522. 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);
  1523. }
  1524. }
  1525.  
  1526. //store in real part in channels[0] and imaginary part in channels[1]
  1527. for (int i = 0; i < src.rows; ++i) {
  1528. for (int j = 0; j < src.cols; ++j) {
  1529. channels[0].at<float>(i, j) = mag.at<float>(i, j) * cos(phi.at<float>(i, j));
  1530. channels[1].at<float>(i, j) = mag.at<float>(i, j) * sin(phi.at<float>(i, j));
  1531. }
  1532. }
  1533. //perform inverse transform and put results in dstf
  1534. Mat dst, dstf;
  1535. merge(channels, 2, fourier);
  1536. dft(fourier, dstf, DFT_INVERSE | DFT_REAL_OUTPUT | DFT_SCALE);
  1537. //inverse centering transformation
  1538. centering_transform(dstf);
  1539. //normalize the result and put in the destination image
  1540. normalize(dstf, dst, 0, 255, NORM_MINMAX, CV_8UC1);
  1541. imshow("DST", dst);
  1542. return dst;
  1543. }
  1544.  
  1545. void lab92() {
  1546. Mat src;
  1547. // Read image from file
  1548. char fname[MAX_PATH];
  1549. while (openFileDlg(fname))
  1550. {
  1551. src = imread(fname, 0);
  1552. generic_frequency_domain_filter(src);
  1553.  
  1554. imshow("Opened Image", src);
  1555. waitKey(0);
  1556. }
  1557. }
  1558.  
  1559. Mat_<float> constructFilter(int w) {
  1560. Mat_<float> toReturn(w, w);
  1561. float o = w / 6.0;
  1562. for (int i = 0; i < w; ++i) {
  1563. for (int j = 0; j < w; ++j) {
  1564. 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))));
  1565. std::cout << toReturn(i, j) << ' ';
  1566. }
  1567. std::cout << '\n';
  1568. }
  1569. return toReturn;
  1570. }
  1571.  
  1572. void lab10() {
  1573. Mat_<uchar> src;
  1574. // Read image from file
  1575. char fname[MAX_PATH];
  1576. while (openFileDlg(fname))
  1577. {
  1578. src = imread(fname, 0);
  1579.  
  1580. double t = (double)getTickCount();
  1581. Mat_<float> matConvoluted = convolute(src, constructFilter(5));
  1582. Mat_<uchar> result = normalizeMat(matConvoluted, 0, 255);
  1583.  
  1584. t = ((double)getTickCount() - t) / getTickFrequency();
  1585. std::cout << "\nTime was:\n" << t * 1000;
  1586.  
  1587. imshow("Src", src);
  1588. imshow("Res", result);
  1589. waitKey(0);
  1590. }
  1591. }
  1592.  
  1593. void lab10_2() {
  1594. Mat_<uchar> src;
  1595. // Read image from file
  1596. char fname[MAX_PATH];
  1597. while (openFileDlg(fname))
  1598. {
  1599. src = imread(fname, 0);
  1600.  
  1601. double t = (double)getTickCount();
  1602.  
  1603. int w = 5;
  1604. float o = w / 6.0;
  1605. Mat_<float> filter = constructFilter(w);
  1606.  
  1607. Mat_<float> Gx(1, w);
  1608. Mat_<float> Gy(w, 1);
  1609.  
  1610. for (int i = 0; i < w; ++i) {
  1611. Gx(0, i) = 1 / (sqrt(2 * PI) * o) * pow(M_E, -(pow(i - w / 2, 2) / (2 * pow(o, 2))));
  1612. Gy(i, 0) = 1 / (sqrt(2 * PI) * o) * pow(M_E, -(pow(i - w / 2, 2) / (2 * pow(o, 2))));
  1613. }
  1614.  
  1615. Mat_<uchar> mat_gx = convolute(src, Gx);
  1616.  
  1617. Mat_<uchar> mat_gy = convolute(mat_gx, Gy);
  1618.  
  1619. t = ((double)getTickCount() - t) / getTickFrequency();
  1620. std::cout << "\nTime was:\n" << t * 1000;
  1621.  
  1622. imshow("Gx", mat_gx);
  1623. imshow("Gy", mat_gy);
  1624.  
  1625. //Mat_<uchar> mat_gy = convolute(mat_gx, fil)
  1626.  
  1627. imshow("Src2", src);
  1628. waitKey(0);
  1629. }
  1630. }
  1631.  
  1632. void lab10_3() {
  1633. Mat_<uchar> src;
  1634. // Read image from file
  1635. char fname[MAX_PATH];
  1636. while (openFileDlg(fname))
  1637. {
  1638. src = imread(fname, 0);
  1639.  
  1640. Mat_<uchar> result(src.rows, src.cols);
  1641. int w = 5;
  1642.  
  1643. for (int i = 0; i < src.rows; ++i) {
  1644. for (int j = 0; j < src.cols; ++j) {
  1645.  
  1646. std::vector<int> v;
  1647.  
  1648. for (int ii = 0; ii < w; ++ii) {
  1649. for (int jj = 0; jj < w; ++jj) {
  1650. if (isInside(src, i+ii, j+jj)) {
  1651. v.push_back(src(i+ii, j+jj));
  1652. }
  1653. }
  1654. }
  1655.  
  1656. std::sort(v.begin(), v.end());
  1657. result(i, j) = v.at(v.size() / 2);
  1658. }
  1659. }
  1660.  
  1661.  
  1662. imshow("Src3", src);
  1663. imshow("Result", result);
  1664. waitKey(0);
  1665. }
  1666. }
  1667.  
  1668. //Mat_<float> toMat_(Mat source) {
  1669. // Mat_<float> toReturn(source.rows, source.cols);
  1670. // for (int i = 0; i < source.rows; i++) {
  1671. // for (int j = 0; j < source.cols; ++j) {
  1672. //
  1673. // }
  1674. // }
  1675. //}
  1676.  
  1677. Mat_<uchar> three_way(Mat_<float> src) {
  1678. Mat_<uchar> res(src.rows, src.cols);
  1679.  
  1680. for (int i = 0; i < src.rows; i++) {
  1681. for (int j = 0; j < src.cols; j++) {
  1682. if (src(i, j) < 90) {
  1683. res(i, j) = 0;
  1684. }
  1685. else {
  1686. if (src(i, j) < 180) {
  1687. res(i, j) = 128;
  1688. }
  1689. else {
  1690. res(i, j) = 255;
  1691. }
  1692. }
  1693. }
  1694. }
  1695. return res;
  1696. }
  1697.  
  1698. void lab11() {
  1699. Mat_<uchar> src;
  1700. // Read image from file
  1701. char fname[MAX_PATH];
  1702. while (openFileDlg(fname))
  1703. {
  1704. src = imread(fname, 0);
  1705.  
  1706. float dx[9] = {
  1707. (float)-1, (float)0, (float)1,
  1708. (float)-2, (float)0, (float)2,
  1709. (float)-1, (float)0, (float)1
  1710. };
  1711.  
  1712. float dy[9] = {
  1713. (float)1, (float)2, (float)1,
  1714. (float)0, (float)0, (float)0,
  1715. (float)-1, (float)-2, (float)-1
  1716. };
  1717.  
  1718. int neighi[] = { 0, -1, -1, -1, 0, 1, 1, 1 };
  1719. int neighj[] = { 1, 1, 0, -1, -1, -1, 0, 1 };
  1720.  
  1721. Mat theDx(3, 3, CV_32FC1, dx);
  1722. Mat theDy(3, 3, CV_32FC1, dy);
  1723.  
  1724. Mat_<float> resDX = convolute(src, theDx);
  1725. Mat_<float> resDY = convolute(src, theDy);
  1726.  
  1727. imshow("DX", abs(resDX / 255));
  1728. imshow("DY", abs(resDY / 255));
  1729.  
  1730. Mat_<float> angle(src.rows, src.cols);
  1731. Mat_<float> magnitude(src.rows, src.cols);
  1732.  
  1733. for (int i = 0; i < src.rows; ++i) {
  1734. for (int j = 0; j < src.cols; ++j) {
  1735. angle(i, j) = atan2(resDY(i, j), resDX(i, j));
  1736. magnitude(i, j) = sqrt(resDX(i, j) * resDX(i, j) + resDY(i, j) * resDY(i, j));
  1737. }
  1738. }
  1739.  
  1740. imshow("Angle", abs(angle / 2 * PI));
  1741. imshow("Magnitude", magnitude / 255);
  1742.  
  1743. Mat_<float> magnitudeFinal(src.rows, src.cols);
  1744.  
  1745. for (int i = 0; i < src.rows; ++i) {
  1746. for (int j = 0; j < src.cols; ++j) {
  1747. float value;
  1748. if (angle(i, j) < 0) {
  1749. value = angle(i, j) + (2 * PI);
  1750. }
  1751. else {
  1752. value = angle(i, j);
  1753. }
  1754. int beta = floor((value * 8 / (2 * PI)) + 0.5);
  1755. beta %= 8;
  1756.  
  1757. int otherBeta = (beta + 4) % 8;
  1758. //bool marked = false;
  1759.  
  1760. if (!isInside(src, i + neighi[beta], j + neighj[beta]) || !isInside(src, i + neighi[otherBeta], j + neighj[otherBeta])) {
  1761. magnitudeFinal(i, j) = magnitude(i, j);
  1762. }
  1763. else {
  1764. if (magnitude(i + neighi[beta], j + neighj[beta]) >= magnitude(i, j) || magnitude(i + neighi[otherBeta], j + neighj[otherBeta]) >= magnitude(i, j)) {
  1765. magnitudeFinal(i, j) = 0;
  1766. }
  1767. else {
  1768. magnitudeFinal(i, j) = magnitude(i, j);
  1769. }
  1770. }
  1771.  
  1772. }
  1773. }
  1774.  
  1775.  
  1776.  
  1777. Mat_<uchar> three = three_way(magnitudeFinal);
  1778.  
  1779. Mat_<uchar> link = three.clone();
  1780.  
  1781. for (int i = 0; i < link.rows; i++) {
  1782. for (int j = 0; j < link.cols; j++) {
  1783. if (link(i, j) == 255) {
  1784. std::queue<Point2i> Queue;
  1785. Queue.push(Point2i(i, j));
  1786. while (!Queue.empty()) {
  1787. Point2i pixel = Queue.front();
  1788. Queue.pop();
  1789. for (int k = 0; k < 8; k++) {
  1790. if (isInside(link, pixel.x + neighi[k], pixel.y + neighj[k])) {
  1791. if (link(pixel.x + neighi[k], pixel.y + neighj[k]) == 128) {
  1792. link(pixel.x + neighi[k], pixel.y + neighj[k]) = 255;
  1793. Queue.push(Point2i(pixel.x + neighi[k], pixel.y + neighj[k]));
  1794. }
  1795. }
  1796. }
  1797. }
  1798.  
  1799. }
  1800. }
  1801. }
  1802.  
  1803. for (int i = 0; i < link.rows; i++) {
  1804. for (int j = 0; j < link.cols; j++) {
  1805. if (link(i, j) == 128) {
  1806. link(i, j) = 0;
  1807. }
  1808. }
  1809. }
  1810.  
  1811.  
  1812. imshow("MAG FINAL", magnitudeFinal / 255);
  1813. imshow("Three way", three);
  1814. imshow("link", link);
  1815. imshow("src", src);
  1816. waitKey(0);
  1817. }
  1818. }
  1819.  
  1820. void lab12() {
  1821. Mat_<uchar> src;
  1822. // Read image from file
  1823. char fname[MAX_PATH];
  1824. while (openFileDlg(fname))
  1825. {
  1826. src = imread(fname, 0);
  1827. Mat_<uchar> result = src.clone();
  1828.  
  1829. int neigi[] = { 0, -1, 0, 1 };
  1830. int neigj[] = { 1, 0, -1, 0 };
  1831.  
  1832. uchar bg = 255;
  1833.  
  1834. for (int i = 0; i < src.rows; ++i) {
  1835. for (int j = 0; j < src.cols; ++j) {
  1836. boolean insider = true;
  1837. for (int k = 0; k < 4; ++k) {
  1838. if (isInside(src, i + neigi[k], j + neigj[k])) {
  1839. if (src(i + neigi[k], j + neigj[k]) == bg) {
  1840. insider = false;
  1841. }
  1842. }
  1843. }
  1844. if (insider) {
  1845. result(i, j) = src(i, j);
  1846. }
  1847. else {
  1848. result(i, j) = bg;
  1849. }
  1850.  
  1851. }
  1852. }
  1853. imshow("Result", result);
  1854. imshow("src", src);
  1855. waitKey(0);
  1856. }
  1857. }
  1858.  
  1859.  
  1860.  
  1861.  
  1862. int main()
  1863. {
  1864. //lab12 e doar erosion
  1865. //lab12();
  1866.  
  1867. //lab11();
  1868.  
  1869. //lab10();
  1870. //lab10_2();
  1871. //lab10_3();
  1872.  
  1873. //lab9();
  1874. //lab92();
  1875.  
  1876.  
  1877. //lab8();
  1878.  
  1879. //dilatate();
  1880.  
  1881. //drawWithChainCode();
  1882. //borderTrace();
  1883.  
  1884. //testMouseClick();
  1885.  
  1886. //copyRGBs();
  1887.  
  1888. //fromColorToRGB();
  1889.  
  1890. //int threshold;
  1891. //scanf("%d", &threshold);
  1892. //printf("%d", threshold);
  1893. //convertBlackAndWhite(threshold);
  1894.  
  1895. //computeHSV();
  1896.  
  1897. /*Mat img = imread("Images/Lena_24bits.bmp", CV_LOAD_IMAGE_COLOR);
  1898. if (isInside(img, 50, 50)) {
  1899. printf("It is");
  1900. }
  1901. else {
  1902. printf("It's not");
  1903. }*/
  1904.  
  1905. //int op;
  1906. //do
  1907. //{
  1908. // system("cls");
  1909. // destroyAllWindows();
  1910. // printf("Menu:\n");
  1911. // printf(" 1 - Open image\n");
  1912. // printf(" 2 - Open BMP images from folder\n");
  1913. // printf(" 3 - Image negative - diblook style\n");
  1914. // printf(" 4 - BGR->HSV\n");
  1915. // printf(" 5 - Resize image\n");
  1916. // printf(" 6 - Canny edge detection\n");
  1917. // printf(" 7 - Edges in a video sequence\n");
  1918. // printf(" 8 - Snap frame from live video\n");
  1919. // printf(" 9 - Mouse callback demo\n");
  1920. // printf(" 0 - Exit\n\n");
  1921. // printf("Option: ");
  1922. // scanf("%d",&op);
  1923. // switch (op)
  1924. // {
  1925. // case 1:
  1926. // testOpenImage();
  1927. // break;
  1928. // case 2:
  1929. // testOpenImagesFld();
  1930. // break;
  1931. // case 3:
  1932. // testParcurgereSimplaDiblookStyle(); //diblook style
  1933. // break;
  1934. // case 4:
  1935. // //testColor2Gray();
  1936. // testBGR2HSV();
  1937. // break;
  1938. // case 5:
  1939. // testResize();
  1940. // break;
  1941. // case 6:
  1942. // testCanny();
  1943. // break;
  1944. // case 7:
  1945. // testVideoSequence();
  1946. // break;
  1947. // case 8:
  1948. // testSnap();
  1949. // break;
  1950. // case 9:
  1951. // testMouseClick();
  1952. // break;
  1953. // }
  1954. //}
  1955. //while (op!=0);
  1956. return 0;
  1957. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement