Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 31.29 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 <random>
  7.  
  8.  
  9. void testOpenImage()
  10. {
  11. char fname[MAX_PATH];
  12. while(openFileDlg(fname))
  13. {
  14. Mat src;
  15. src = imread(fname);
  16. imshow("image",src);
  17. waitKey();
  18. }
  19. }
  20.  
  21. void testOpenImagesFld()
  22. {
  23. char folderName[MAX_PATH];
  24. if (openFolderDlg(folderName)==0)
  25. return;
  26. char fname[MAX_PATH];
  27. FileGetter fg(folderName,"bmp");
  28. while(fg.getNextAbsFile(fname))
  29. {
  30. Mat src;
  31. src = imread(fname);
  32. imshow(fg.getFoundFileName(),src);
  33. if (waitKey()==27) //ESC pressed
  34. break;
  35. }
  36. }
  37.  
  38. void testImageOpenAndSave()
  39. {
  40. Mat src, dst;
  41.  
  42. src = imread("Images/Lena_24bits.bmp", CV_LOAD_IMAGE_COLOR); // Read the image
  43.  
  44. if (!src.data) // Check for invalid input
  45. {
  46. printf("Could not open or find the image\n");
  47. return;
  48. }
  49.  
  50. // Get the image resolution
  51. Size src_size = Size(src.cols, src.rows);
  52.  
  53. // Display window
  54. const char* WIN_SRC = "Src"; //window for the source image
  55. namedWindow(WIN_SRC, CV_WINDOW_AUTOSIZE);
  56. cvMoveWindow(WIN_SRC, 0, 0);
  57.  
  58. const char* WIN_DST = "Dst"; //window for the destination (processed) image
  59. namedWindow(WIN_DST, CV_WINDOW_AUTOSIZE);
  60. cvMoveWindow(WIN_DST, src_size.width + 10, 0);
  61.  
  62. cvtColor(src, dst, CV_BGR2GRAY); //converts the source image to a grayscale one
  63.  
  64. imwrite("Images/Lena_24bits_gray.bmp", dst); //writes the destination to file
  65.  
  66. imshow(WIN_SRC, src);
  67. imshow(WIN_DST, dst);
  68.  
  69. printf("Press any key to continue ...\n");
  70. waitKey(0);
  71. }
  72.  
  73. void testNegativeImage()
  74. {
  75. char fname[MAX_PATH];
  76. while(openFileDlg(fname))
  77. {
  78. double t = (double)getTickCount(); // Get the current time [s]
  79.  
  80. Mat src = imread(fname,CV_LOAD_IMAGE_GRAYSCALE);
  81. int height = src.rows;
  82. int width = src.cols;
  83. Mat dst = Mat(height,width,CV_8UC1);
  84. // Asa se acceseaaza pixelii individuali pt. o imagine cu 8 biti/pixel
  85. // Varianta ineficienta (lenta)
  86. for (int i=0; i<height; i++)
  87. {
  88. for (int j=0; j<width; j++)
  89. {
  90. uchar val = src.at<uchar>(i,j);
  91. uchar neg = 255 - val;
  92. dst.at<uchar>(i,j) = neg;
  93. }
  94. }
  95.  
  96. // Get the current time again and compute the time difference [s]
  97. t = ((double)getTickCount() - t) / getTickFrequency();
  98. // Print (in the console window) the processing time in [ms]
  99. printf("Time = %.3f [ms]\n", t * 1000);
  100.  
  101. imshow("input image",src);
  102. imshow("negative image",dst);
  103. waitKey();
  104. }
  105. }
  106.  
  107. void testParcurgereSimplaDiblookStyle()
  108. {
  109. char fname[MAX_PATH];
  110. while (openFileDlg(fname))
  111. {
  112. Mat src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
  113. int height = src.rows;
  114. int width = src.cols;
  115. Mat dst = src.clone();
  116.  
  117. double t = (double)getTickCount(); // Get the current time [s]
  118.  
  119. // the fastest approach using the “diblook style”
  120. uchar *lpSrc = src.data;
  121. uchar *lpDst = dst.data;
  122. int w = (int) src.step; // no dword alignment is done !!!
  123. for (int i = 0; i<height; i++)
  124. for (int j = 0; j < width; j++) {
  125. uchar val = lpSrc[i*w + j];
  126. lpDst[i*w + j] = 255 - val;
  127. }
  128.  
  129. // Get the current time again and compute the time difference [s]
  130. t = ((double)getTickCount() - t) / getTickFrequency();
  131. // Print (in the console window) the processing time in [ms]
  132. printf("Time = %.3f [ms]\n", t * 1000);
  133.  
  134. imshow("input image",src);
  135. imshow("negative image",dst);
  136. waitKey();
  137. }
  138. }
  139.  
  140. void testColor2Gray()
  141. {
  142. char fname[MAX_PATH];
  143. while(openFileDlg(fname))
  144. {
  145. Mat src = imread(fname);
  146.  
  147. int height = src.rows;
  148. int width = src.cols;
  149.  
  150. Mat dst = Mat(height,width,CV_8UC1);
  151.  
  152. // Asa se acceseaaza pixelii individuali pt. o imagine RGB 24 biti/pixel
  153. // Varianta ineficienta (lenta)
  154. for (int i=0; i<height; i++)
  155. {
  156. for (int j=0; j<width; j++)
  157. {
  158. Vec3b v3 = src.at<Vec3b>(i,j);
  159. uchar b = v3[0];
  160. uchar g = v3[1];
  161. uchar r = v3[2];
  162. dst.at<uchar>(i,j) = (r+g+b)/3;
  163. }
  164. }
  165.  
  166. imshow("input image",src);
  167. imshow("gray image",dst);
  168. waitKey();
  169. }
  170. }
  171.  
  172. void testBGR2HSV()
  173. {
  174. char fname[MAX_PATH];
  175. while (openFileDlg(fname))
  176. {
  177. Mat src = imread(fname);
  178. int height = src.rows;
  179. int width = src.cols;
  180.  
  181. // Componentele d eculoare ale modelului HSV
  182. Mat H = Mat(height, width, CV_8UC1);
  183. Mat S = Mat(height, width, CV_8UC1);
  184. Mat V = Mat(height, width, CV_8UC1);
  185.  
  186. // definire pointeri la matricele (8 biti/pixeli) folosite la afisarea componentelor individuale H,S,V
  187. uchar* lpH = H.data;
  188. uchar* lpS = S.data;
  189. uchar* lpV = V.data;
  190.  
  191. Mat hsvImg;
  192. cvtColor(src, hsvImg, CV_BGR2HSV);
  193.  
  194. // definire pointer la matricea (24 biti/pixeli) a imaginii HSV
  195. uchar* hsvDataPtr = hsvImg.data;
  196.  
  197. for (int i = 0; i<height; i++)
  198. {
  199. for (int j = 0; j<width; j++)
  200. {
  201. int hi = i*width * 3 + j * 3;
  202. int gi = i*width + j;
  203.  
  204. lpH[gi] = hsvDataPtr[hi] * 510 / 360; // lpH = 0 .. 255
  205. lpS[gi] = hsvDataPtr[hi + 1]; // lpS = 0 .. 255
  206. lpV[gi] = hsvDataPtr[hi + 2]; // lpV = 0 .. 255
  207. }
  208. }
  209.  
  210. imshow("input image", src);
  211. imshow("H", H);
  212. imshow("S", S);
  213. imshow("V", V);
  214.  
  215. waitKey();
  216. }
  217. }
  218.  
  219. void testResize()
  220. {
  221. char fname[MAX_PATH];
  222. while(openFileDlg(fname))
  223. {
  224. Mat src;
  225. src = imread(fname);
  226. Mat dst1,dst2;
  227. //without interpolation
  228. resizeImg(src,dst1,320,false);
  229. //with interpolation
  230. resizeImg(src,dst2,320,true);
  231. imshow("input image",src);
  232. imshow("resized image (without interpolation)",dst1);
  233. imshow("resized image (with interpolation)",dst2);
  234. waitKey();
  235. }
  236. }
  237.  
  238. void testCanny()
  239. {
  240. char fname[MAX_PATH];
  241. while(openFileDlg(fname))
  242. {
  243. Mat src,dst,gauss;
  244. src = imread(fname,CV_LOAD_IMAGE_GRAYSCALE);
  245. double k = 0.4;
  246. int pH = 50;
  247. int pL = (int) k*pH;
  248. GaussianBlur(src, gauss, Size(5, 5), 0.8, 0.8);
  249. Canny(gauss,dst,pL,pH,3);
  250. imshow("input image",src);
  251. imshow("canny",dst);
  252. waitKey();
  253. }
  254. }
  255.  
  256. void testVideoSequence()
  257. {
  258. VideoCapture cap("Videos/rubic.avi"); // off-line video from file
  259. //VideoCapture cap(0); // live video from web cam
  260. if (!cap.isOpened()) {
  261. printf("Cannot open video capture device.\n");
  262. waitKey(0);
  263. return;
  264. }
  265.  
  266. Mat edges;
  267. Mat frame;
  268. char c;
  269.  
  270. while (cap.read(frame))
  271. {
  272. Mat grayFrame;
  273. cvtColor(frame, grayFrame, CV_BGR2GRAY);
  274. Canny(grayFrame,edges,40,100,3);
  275. imshow("source", frame);
  276. imshow("gray", grayFrame);
  277. imshow("edges", edges);
  278. c = cvWaitKey(0); // waits a key press to advance to the next frame
  279. if (c == 27) {
  280. // press ESC to exit
  281. printf("ESC pressed - capture finished\n");
  282. break; //ESC pressed
  283. };
  284. }
  285. }
  286.  
  287.  
  288. void testSnap()
  289. {
  290. VideoCapture cap(0); // open the deafult camera (i.e. the built in web cam)
  291. if (!cap.isOpened()) // openenig the video device failed
  292. {
  293. printf("Cannot open video capture device.\n");
  294. return;
  295. }
  296.  
  297. Mat frame;
  298. char numberStr[256];
  299. char fileName[256];
  300.  
  301. // video resolution
  302. Size capS = Size((int)cap.get(CV_CAP_PROP_FRAME_WIDTH),
  303. (int)cap.get(CV_CAP_PROP_FRAME_HEIGHT));
  304.  
  305. // Display window
  306. const char* WIN_SRC = "Src"; //window for the source frame
  307. namedWindow(WIN_SRC, CV_WINDOW_AUTOSIZE);
  308. cvMoveWindow(WIN_SRC, 0, 0);
  309.  
  310. const char* WIN_DST = "Snapped"; //window for showing the snapped frame
  311. namedWindow(WIN_DST, CV_WINDOW_AUTOSIZE);
  312. cvMoveWindow(WIN_DST, capS.width + 10, 0);
  313.  
  314. char c;
  315. int frameNum = -1;
  316. int frameCount = 0;
  317.  
  318. for (;;)
  319. {
  320. cap >> frame; // get a new frame from camera
  321. if (frame.empty())
  322. {
  323. printf("End of the video file\n");
  324. break;
  325. }
  326.  
  327. ++frameNum;
  328.  
  329. imshow(WIN_SRC, frame);
  330.  
  331. c = cvWaitKey(10); // waits a key press to advance to the next frame
  332. if (c == 27) {
  333. // press ESC to exit
  334. printf("ESC pressed - capture finished");
  335. break; //ESC pressed
  336. }
  337. if (c == 115){ //'s' pressed - snapp the image to a file
  338. frameCount++;
  339. fileName[0] = NULL;
  340. sprintf(numberStr, "%d", frameCount);
  341. strcat(fileName, "Images/A");
  342. strcat(fileName, numberStr);
  343. strcat(fileName, ".bmp");
  344. bool bSuccess = imwrite(fileName, frame);
  345. if (!bSuccess)
  346. {
  347. printf("Error writing the snapped image\n");
  348. }
  349. else
  350. imshow(WIN_DST, frame);
  351. }
  352. }
  353.  
  354. }
  355.  
  356. float computeElongationAxis(Mat_<Vec3b> src, Vec3b color, int iCenter, int jCenter)
  357. {
  358. int cols = src.cols;
  359. int rows = src.rows;
  360. int s1 = 0, s2 = 0;
  361. for (int i = 0; i < rows; i++)
  362. {
  363. for (int j = 0; j < cols; j++)
  364. {
  365. if (src(i, j) == color)
  366. {
  367. s1 = s1 + (i - iCenter)*(j - jCenter);
  368. s2 = s2 +(j - jCenter)*(j - jCenter) - (i - iCenter)*(i - iCenter);
  369.  
  370. }
  371. }
  372. }
  373. s1 = s1*2;
  374. return atan2(s1, s2)/ 2.0f;
  375.  
  376. }
  377.  
  378. Point computeCenterOfMass(Mat_<Vec3b> src, Vec3b selectedColor, int Area ) {
  379. int cols = src.cols;
  380. int rows = src.rows;
  381. int iCenter = 0, jCenter = 0;
  382. for (int i = 0; i < rows; i++) {
  383. for (int j = 0; j < cols; j++) {
  384. if (src(i, j) == selectedColor) {
  385.  
  386. iCenter = iCenter + i;
  387. jCenter = jCenter + j;
  388. }
  389. }
  390. }
  391. iCenter = iCenter / Area;
  392. jCenter = jCenter / Area;
  393. return Point(jCenter, iCenter);
  394. }
  395.  
  396. int computeArea(Mat_<Vec3b> src, Vec3b selectedColor)
  397. {
  398. int Area = 0;
  399. for (int i = 0; i < src.rows; i++)
  400. {
  401. for (int j = 0; j < src.cols; j++)
  402. {
  403. if (src(i, j) == selectedColor)
  404. {
  405. Area++;
  406. }
  407. }
  408. }
  409. return Area;
  410. }
  411.  
  412. void MyCallBackFunc(int event, int x, int y, int flags, void* param)
  413. {
  414. //More examples: http://opencvexamples.blogspot.com/2014/01/detect-mouse-clicks-and-moves-on-image.html
  415. Mat_<Vec3b>* src = (Mat_<Vec3b>*)param;
  416. Mat_<Vec3b> copy;
  417. Vec3b selectedColor;
  418. Point centerOfMass;
  419. Point Point1, Point2;
  420. float angleRad, angleDegree;
  421. if (event == CV_EVENT_LBUTTONDOWN)
  422. {
  423. copy = *src;
  424. printf("Pos(x,y): %d,%d Color(RGB): %d,%d,%d\n",
  425. x, y,
  426. (int)(*src).at<Vec3b>(y, x)[2],
  427. (int)(*src).at<Vec3b>(y, x)[1],
  428. (int)(*src).at<Vec3b>(y, x)[0]);
  429. selectedColor = (*src).at<Vec3b>(y, x);
  430. int Area = computeArea(*src, selectedColor);
  431. printf("%d\n", Area);
  432. centerOfMass = computeCenterOfMass(*src, selectedColor, Area);
  433. printf("%d , %d\n", centerOfMass.x, centerOfMass.y);
  434. circle(copy, centerOfMass, 5, Scalar(255, 0, 255), -1);
  435. imshow("Copy", copy);
  436. angleRad = computeElongationAxis(*src, selectedColor, centerOfMass.y, centerOfMass.x);
  437. angleDegree = angleRad * 180 / 3, 14;
  438. printf("%f\n", angleDegree);
  439. Point1.x = centerOfMass.x - 30;
  440. Point2.x = centerOfMass.x + 30;
  441. int y = 30 * tan(angleRad);
  442. Point1.y = centerOfMass.y - y;
  443. Point2.y = centerOfMass.y + y;
  444. line(copy, Point1, Point2, Scalar(0, 0, 0));
  445. }
  446.  
  447. }
  448.  
  449. void testMouseClick()
  450. {
  451. Mat src;
  452. // Read image from file
  453. char fname[MAX_PATH];
  454. while (openFileDlg(fname))
  455. {
  456. src = imread(fname);
  457. //Create a window
  458. namedWindow("My Window", 1);
  459.  
  460. //set the callback function for any mouse event
  461. setMouseCallback("My Window", MyCallBackFunc, &src);
  462.  
  463. //show the image
  464. imshow("My Window", src);
  465.  
  466. // Wait until user press some key
  467. waitKey(0);
  468. }
  469. }
  470.  
  471. /* Histogram display function - display a histogram using bars (simlilar to L3 / PI)
  472. Input:
  473. name - destination (output) window name
  474. hist - pointer to the vector containing the histogram values
  475. hist_cols - no. of bins (elements) in the histogram = histogram image width
  476. hist_height - height of the histogram image
  477. Call example:
  478. showHistogram ("MyHist", hist_dir, 255, 200);
  479. */
  480. void showHistogram(const std::string& name, int* hist, const int hist_cols, const int hist_height)
  481. {
  482. Mat imgHist(hist_height, hist_cols, CV_8UC3, CV_RGB(255, 255, 255)); // constructs a white image
  483.  
  484. //computes histogram maximum
  485. int max_hist = 0;
  486. for (int i = 0; i<hist_cols; i++)
  487. if (hist[i] > max_hist)
  488. max_hist = hist[i];
  489. double scale = 1.0;
  490. scale = (double)hist_height / max_hist;
  491. int baseline = hist_height - 1;
  492.  
  493. for (int x = 0; x < hist_cols; x++) {
  494. Point p1 = Point(x, baseline);
  495. Point p2 = Point(x, baseline - cvRound(hist[x] * scale));
  496. line(imgHist, p1, p2, CV_RGB(255, 0, 255)); // histogram bins colored in magenta
  497. }
  498.  
  499. imshow(name, imgHist);
  500.  
  501. }
  502.  
  503. void copy_RGB()
  504. {
  505. char filename[MAX_PATH];
  506. openFileDlg(filename);
  507. Mat_<Vec3b> src;
  508. src = imread(filename); ///opencv returns BGR
  509. imshow("image", src);
  510.  
  511. Mat_<uchar> r(src.rows,src.cols);
  512. Mat_<uchar> g(src.rows,src.cols);
  513. Mat_<uchar> b(src.rows,src.cols);
  514.  
  515. for (int i = 0; i < src.rows; i++)
  516. {
  517. for (int j = 0; j < src.cols; j++)
  518. {
  519. b(i, j) = src(i, j)[0];
  520. g(i, j) = src(i, j)[1];
  521. r(i, j) = src(i, j)[2];
  522. }
  523. }
  524.  
  525. imshow("blue", b);
  526. imshow("green", g);
  527. imshow("red", r);
  528. waitKey();
  529.  
  530. }
  531.  
  532. void convert_to_grayscale()
  533. {
  534. char filename[MAX_PATH];
  535. openFileDlg(filename);
  536. Mat_<Vec3b> src;
  537. src = imread(filename);
  538. imshow("image", src);
  539.  
  540. Mat_<uchar> grayscale(src.rows,src.cols);
  541.  
  542. for (int i = 0; i < src.rows; i++)
  543. {
  544. for (int j = 0; j < src.cols; j++)
  545. {
  546. grayscale(i, j) = (src(i, j)[0] + src(i, j)[1] + src(i, j)[2]) / 3;
  547. }
  548. }
  549.  
  550. imshow("grayscale", grayscale);
  551. waitKey();
  552.  
  553. }
  554.  
  555. void convert_to_binary()
  556. {
  557. char filename[MAX_PATH];
  558. openFileDlg(filename);
  559. Mat_<uchar> src;
  560. src = imread(filename,0);
  561.  
  562. int treshold;
  563.  
  564. Mat_<uchar> binary(src.rows,src.cols);
  565. std::cout << "Treshold: ";
  566. std::cin >> treshold;
  567. std::cout << "\n";
  568.  
  569. for (int i = 0; i < src.rows; i++)
  570. {
  571. for (int j = 0; j < src.cols; j++)
  572. {
  573. if (src(i, j) < treshold)
  574. {
  575. binary(i, j) = 0;
  576. }
  577.  
  578. else
  579. {
  580. binary(i, j) = 255;
  581. }
  582. }
  583. }
  584. imshow("image", src);
  585. imshow("binary", binary);
  586. waitKey();
  587.  
  588. }
  589.  
  590. void compute_HSV()
  591. {
  592. char filename[MAX_PATH];
  593. openFileDlg(filename);
  594. Mat_<Vec3b> src;
  595. src = imread(filename);
  596. float r, g, b, m, M, C, V, H, S;
  597.  
  598. Mat_<uchar> h(src.rows, src.cols);
  599. Mat_<uchar> s(src.rows, src.cols);
  600. Mat_<uchar> v(src.rows,src.cols);
  601.  
  602. for (int i = 0; i < src.rows; i++)
  603. {
  604. for (int j = 0; j < src.cols; j++)
  605. {
  606. r = (float)src(i, j)[2] / 255;
  607. g = (float)src(i, j)[1] / 255;
  608. b = (float)src(i, j)[0] / 255;
  609. M = max(max(r, g), b);
  610. m = min(min(r, g), b);
  611. C = M - m;
  612. V = M;
  613.  
  614. if (V != 0)
  615. {
  616. S = C / V;
  617. }
  618. else
  619. {
  620. S = 0;
  621. }
  622.  
  623. if (C != 0)
  624. {
  625. if (M == r)
  626. {
  627. H = 60 * (g - b) / C;
  628. }
  629.  
  630. if (M == g)
  631. {
  632. H = 120 + 60 * (b - r) / C;
  633. }
  634.  
  635. if (M == b)
  636. {
  637. H = 240 + 60 * (r - g) / C;
  638. }
  639. }
  640. else
  641. {
  642. H = 0;
  643. }
  644.  
  645. if (H < 0)
  646. {
  647. H = H + 360;
  648. }
  649.  
  650. uchar H_norm = H * 255 / 360;
  651. uchar S_norm = S * 255;
  652. uchar V_norm = V * 255;
  653. h(i, j) = H_norm;
  654. s(i, j) = S_norm;
  655. v(i, j) = V_norm;
  656.  
  657. }
  658. }
  659.  
  660. imshow("image", src);
  661. imshow("h", h);
  662. imshow("s", s);
  663. imshow("v", v);
  664. waitKey();
  665.  
  666.  
  667. }
  668.  
  669.  
  670. int* compute_histogram(Mat_<uchar> src) {
  671. int * histogram = new int[256]();
  672. for (int i = 0; i < src.rows; i++) {
  673. for (int j = 0; j < src.cols; j++) {
  674. histogram[src(i, j)]++;
  675. }
  676. }
  677. return histogram;
  678. }
  679.  
  680.  
  681. void test_histogram() {
  682. char filename[MAX_PATH];
  683. int * histogram = new int[256]();
  684. openFileDlg(filename);
  685. Mat_<uchar> src;
  686. src = imread(filename, CV_LOAD_IMAGE_GRAYSCALE);
  687. imshow("image", src);
  688. histogram = compute_histogram(src);
  689. showHistogram("Histogram", histogram, 255, 255);
  690. waitKey();
  691. }
  692.  
  693.  
  694. float * compute_PDF(Mat_<uchar> src) {
  695.  
  696. int * histogram = compute_histogram(src);
  697. float PDF[256];
  698. int M = src.rows * src.cols;
  699. for (int i = 0; i < 256; i++) {
  700. PDF[i] = histogram[i] / M;
  701. }
  702. return PDF;
  703. }
  704.  
  705. void test_PDF() {
  706. char filename[MAX_PATH];
  707. openFileDlg(filename);
  708. Mat_<uchar> src;
  709. src = imread(filename, CV_LOAD_IMAGE_GRAYSCALE);
  710. imshow("image", src);
  711. compute_PDF(src);
  712. waitKey();
  713. }
  714.  
  715. int * compute_bins_histogram(Mat_<uchar> src, int bins) {
  716. int * histogram = new int[bins]();
  717. float N = 256 / bins;
  718. for (int i = 0; i < src.rows; i++) {
  719. for (int j = 0; j < src.cols; j++) {
  720. histogram[(int)(src(i, j)/N)]++;
  721. }
  722. }
  723. return histogram;
  724. }
  725.  
  726.  
  727. void test_bins_histogram() {
  728. printf("Bins=");
  729. int bins;
  730. scanf("%d", &bins);
  731. char filename[MAX_PATH];
  732. int * histogram = new int[bins]();
  733. openFileDlg(filename);
  734. Mat_<uchar> src;
  735. src = imread(filename, CV_LOAD_IMAGE_GRAYSCALE);
  736. imshow("image", src);
  737. histogram = compute_bins_histogram(src,bins);
  738. showHistogram("Histogram", histogram, bins, 255);
  739. waitKey();
  740. }
  741.  
  742.  
  743.  
  744. uchar getMaxima(std::vector<int> maximas, uchar pixel)
  745. {
  746. int minDif = 1000;
  747. int pos;
  748. int dif;
  749. for (int i = 0; i < maximas.size(); i++)
  750. {
  751. dif = std::abs(pixel - maximas[i]);
  752. if (dif < minDif)
  753. {
  754. minDif = dif;
  755. pos = maximas[i];
  756. }
  757. }
  758. return pos;
  759. }
  760.  
  761. std::vector<int> computeMaxima(float* pdf)
  762. {
  763. int WH = 5;
  764. float TH = 0.0003;
  765. float avg = 0;
  766. bool maxima = true;
  767. std::vector<int> maximas;
  768. maximas.push_back(0);
  769. for (int k = WH; k < 255 - WH; k++)
  770. {
  771. maxima = true;
  772. avg = 0;
  773. for (int i = k - WH; i <= k + WH; i++)
  774. {
  775. if (pdf[k] < pdf[i])
  776. {
  777. maxima = false;
  778. }
  779. avg += pdf[i];
  780. }
  781. avg = avg / (2 * WH + 1);
  782. if ((pdf[k] > avg + TH) && maxima)
  783. {
  784.  
  785. maximas.push_back(k);
  786. }
  787.  
  788. if (maxima)
  789. {
  790. }
  791. }
  792. maximas.push_back(255);
  793. return maximas;
  794. }
  795.  
  796. void multilevelThresholding(Mat_<uchar> src, float* pdf)
  797. {
  798. int WH = 5;
  799. float TH = 0.0003;
  800. float avg = 0;
  801. bool maxima = true;
  802. int size = src.cols * src.rows;
  803. Mat_<uchar> dest(src.rows, src.cols);
  804. std::vector<int> maximas;
  805. maximas = computeMaxima(pdf);
  806. uchar pixel;
  807. for (int i = 0; i < src.rows; i++)
  808. {
  809. for (int j = 0; j < src.cols; j++)
  810. {
  811. pixel = src(i, j);
  812. dest(i, j) = getMaxima(maximas, pixel);
  813.  
  814. }
  815. }
  816. imshow("src", src);
  817. imshow("dest", dest);
  818. waitKey();
  819. }
  820.  
  821. void testThresholding()
  822. {
  823. char fname[MAX_PATH];
  824. openFileDlg(fname);
  825. Mat_<uchar> src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
  826. int* hist = compute_histogram(src);
  827. showHistogram("hist", hist, 255, 255);
  828. float* pdf = compute_PDF(src);
  829. multilevelThresholding(src, pdf);
  830. delete[] pdf;
  831. delete[] hist;
  832. }
  833.  
  834. Mat_<uchar> breadth_first_traversal(Mat_<uchar> src) {
  835. int di[8] = { -1, 0, 1, 0, -1, 1, 1, -1 };
  836. int dj[8] = { 0, -1, 0, 1, -1, -1, 1, 1 };
  837. int N;
  838. int label = 0;
  839. int height = src.rows;
  840. int width = src.cols;
  841. Mat_<uchar> labels = Mat_<uchar>::zeros(height, width);
  842.  
  843. printf("Insert neighborhood type(4 or 8):");
  844. scanf("%d", &N);
  845.  
  846.  
  847. for (int i = 0; i < height; i++) {
  848. for (int j = 0; j < width; j++) {
  849. if (src(i, j) == 0 && labels(i, j) == 0){
  850. label++;
  851. printf("New label found\n");
  852. std::queue<Point> Q;
  853. labels(i, j) = label;
  854. Q.push(Point(i, j));
  855. while (!Q.empty()) {
  856. Point q = Q.front();
  857. Q.pop();
  858. for (int k = 0; k < N; k++) {
  859. Point neighbor(q.x+di[k],q.y+dj[k]);
  860. if(neighbor.x>=0 && neighbor.x < src.rows && neighbor.y >=0 && neighbor.y < src.cols){
  861. if (src(neighbor.x, neighbor.y) == 0 && labels(neighbor.x, neighbor.y) == 0) {
  862. labels(neighbor.x, neighbor.y) = label;
  863. Q.push(neighbor);
  864. }
  865. }
  866. }
  867. }
  868. }
  869. }
  870. }
  871.  
  872. return labels;
  873. }
  874.  
  875. Mat_<Vec3b> colorLabels(Mat_<uchar> labels) {
  876.  
  877. std::default_random_engine gen;
  878. std::uniform_int_distribution<int> d(0, 255);
  879. Mat_<Vec3b> destination(labels.rows,labels.cols);
  880. uchar x = d(gen);
  881. std::vector<Vec3b> colors;
  882. for (int i = 0; i < 255; i++) {
  883. colors.push_back(Vec3b(d(gen), d(gen), d(gen)));
  884. }
  885. for (int i = 0; i < labels.rows; i++)
  886. {
  887. for (int j = 0; j < labels.cols; j++)
  888. {
  889. if (labels(i,j)>0) {
  890.  
  891. destination(i, j) = colors[labels(i, j)];
  892. }
  893. else {
  894. destination(i, j) = Vec3b(255,255,255);
  895. }
  896. }
  897. }
  898. return destination;
  899. }
  900.  
  901. void test_breadth_first_traversal() {
  902. char filename[MAX_PATH];
  903. openFileDlg(filename);
  904. Mat_<Vec3b> img;
  905. Mat_<uchar> src;
  906. src = imread(filename, CV_LOAD_IMAGE_GRAYSCALE);
  907. imshow("image", src);
  908. Mat_<uchar> labels = breadth_first_traversal(src);
  909. img = colorLabels(labels);
  910. imshow("labels", labels);
  911. imshow("color labels", img);
  912. waitKey(0);
  913. }
  914.  
  915. Mat_<uchar> label_two_pass(Mat_<uchar> src){
  916. int di[8] = {0,-1,-1,-1,0,1,1,1};
  917. int dj[8] = {-1,-1,0,1,1,1,0,-1};
  918. int label = 0;
  919. int height = src.rows;
  920. int width = src.cols;
  921. Mat_<uchar> labels = Mat_<uchar>::zeros(height, width);
  922. std::vector<std::vector<int>> edges;
  923.  
  924. for (int i = 0; i < height - 1; i++) {
  925. for (int j = 0; j < width; j++) {
  926.  
  927. if (src(i, j) == 0 && labels(i, j) == 0) {
  928.  
  929. std::vector<uchar> L;
  930. for (int k = 0; k < 4; k++) {
  931. Point neighbor(i + di[k], j + dj[k]);
  932. if (neighbor.x >= 0 && neighbor.x < src.rows && neighbor.y >= 0 && neighbor.y < src.cols) {
  933. if (labels(neighbor.x, neighbor.y) > 0) {
  934. L.push_back(labels(neighbor.x, neighbor.y));
  935. }
  936. }
  937. }
  938.  
  939. if (L.size() == 0) {
  940. label++;
  941. labels(i, j) = label;
  942. }
  943. else {
  944. int x = *std::min_element(L.begin(), L.end());
  945. labels(i, j) = x;
  946. for (int k = 0; k < L.size(); k++) {
  947. if (L[k] != x) {
  948. edges.resize(label+1);
  949. edges[x].push_back(L[k]);
  950. edges[L[k]].push_back(x);
  951. }
  952. }
  953. }
  954. }
  955. }
  956. }
  957.  
  958. int newLabel = 0;
  959. int * newLabels = new int[label + 1]();
  960. for (int i = 1; i <= label; i++) {
  961. if (newLabels[i] == 0) {
  962. newLabel++;
  963. std::queue<int> Q;
  964. newLabels[i] = newLabel;
  965. Q.push(i);
  966. while (!Q.empty()) {
  967. int x = Q.front();
  968. Q.pop();
  969. for (int y = 0; y < edges[x].size(); y++) {
  970. if (newLabels[edges[x][y]] == 0) {
  971. newLabels[edges[x][y]] = newLabel;
  972. Q.push(edges[x][y]);
  973. }
  974. }
  975.  
  976.  
  977.  
  978. }
  979. }
  980. }
  981.  
  982. for (int i = 0; i <= height - 1; i++) {
  983. for (int j = 0; j <= width - 1; j++) {
  984. labels(i, j) = newLabels[labels(i, j)];
  985. }
  986. }
  987. return labels;
  988. }
  989.  
  990. void test_label_two_pass() {
  991. char filename[MAX_PATH];
  992. openFileDlg(filename);
  993. Mat_<uchar> src = imread(filename, CV_LOAD_IMAGE_GRAYSCALE);
  994. Mat_<uchar> labels = label_two_pass(src);
  995. Mat_<Vec3b> colors = colorLabels(labels);
  996. imshow("Source", src);
  997. imshow("Labels", labels);
  998. imshow("Colour", colors);
  999. waitKey();
  1000. }
  1001.  
  1002.  
  1003. std::vector<Point> traceBorder(Mat_<uchar> src, std::vector<int> *codeChain) {
  1004.  
  1005. int rows = src.rows;
  1006. int cols = src.cols;
  1007. Mat_<Vec3b> dst(rows, cols);
  1008. int lastDir = 0;
  1009. int di[8] = { 0,-1,-1,-1,0,1,1,1 };
  1010. int dj[8] = { 1,1,0,-1,-1,-1,0,1 };
  1011. int k = 0;
  1012. lastDir = 7;
  1013. std::vector<Point> border;
  1014. for (int i = 0; i < rows; i++)
  1015. {
  1016. for (int j = 0; j < cols; j++)
  1017. {
  1018. if (src(i, j) < 254)
  1019. {
  1020. dst(i, j) = Vec3b(255, 0, 0);
  1021. int k = 0;
  1022.  
  1023. Point startingPoint(j, i);
  1024. Point lastpoint(j, i);
  1025. Point neighbor(-1, -1);
  1026. while (startingPoint != neighbor)
  1027. {
  1028. k = 0;
  1029. if (lastDir % 2 == 0)
  1030. {
  1031. lastDir = (lastDir + 7) % 8;
  1032. }
  1033. else
  1034. {
  1035. lastDir = (lastDir + 6) % 8;
  1036. }
  1037. while (k < 8)
  1038. {
  1039. neighbor = Point(lastpoint.x + dj[lastDir], lastpoint.y + di[lastDir]);
  1040. if (src(neighbor.y,neighbor.x) == src(i, j))
  1041. {
  1042. border.push_back(neighbor);
  1043. codeChain->push_back(lastDir);
  1044. break;
  1045. }
  1046. k++;
  1047. lastDir = (lastDir + 1) % 8;
  1048.  
  1049. }
  1050. lastpoint = neighbor;
  1051. }
  1052. return border;
  1053. }
  1054. else
  1055. {
  1056. dst(i, j) = Vec3b(src(i, j), src(i, j), src(i, j));
  1057. }
  1058. }
  1059. }
  1060.  
  1061. return border;
  1062. }
  1063.  
  1064. void testBorderTracing()
  1065. {
  1066. int n;
  1067. char fname[MAX_PATH];
  1068. openFileDlg(fname);
  1069. std::vector<int> codeChain;
  1070. Mat_<uchar> src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
  1071. Mat_<Vec3b> dst(src.rows, src.cols);
  1072. std::vector<Point> border = traceBorder(src, &codeChain);
  1073. std::vector<int> derivate;
  1074. for (int i = 0; i < src.rows; i++)
  1075. {
  1076. for (int j = 0; j < src.cols; j++)
  1077. {
  1078. dst(i, j) = Vec3b(src(i, j), src(i, j), src(i, j));
  1079. }
  1080. }
  1081. for (int i = 0; i < border.size(); i++)
  1082. {
  1083. dst(border[i]) = Vec3b(0,0,255);
  1084.  
  1085.  
  1086. }
  1087.  
  1088. for (int i = 0; i < codeChain.size(); i++) {
  1089. printf("%d ",codeChain[i]);
  1090. }
  1091.  
  1092. imshow("src", src);
  1093. imshow("dst", dst);
  1094. waitKey(0);
  1095. }
  1096.  
  1097.  
  1098. Mat_<uchar> dillation(Mat_<uchar> src, Mat_<uchar> structure)
  1099. {
  1100. int rows = src.rows;
  1101. int cols = src.cols;
  1102. int width = structure.cols;
  1103. int height = structure.rows;
  1104. Mat_<uchar> dst(rows, cols, 255);
  1105.  
  1106. for (int i = 0; i < rows; i++)
  1107. {
  1108. for (int j = 0; j < cols; j++)
  1109. {
  1110. if (src(i, j) == 0)
  1111. {
  1112. dst(i, j) = 0;
  1113. for (int m = -height / 2; m <= height / 2; m++)
  1114. {
  1115. for (int n = -width / 2; n <= width / 2; n++)
  1116. {
  1117. Point neighbor(j + n, i + m);
  1118. if (neighbor.x >= 0 && neighbor.x < cols && neighbor.y >= 0 && neighbor.y < rows)
  1119. {
  1120. if (structure(m + height / 2, n + width / 2) == 0)
  1121. {
  1122. dst(neighbor) = 0;
  1123. }
  1124. }
  1125.  
  1126. }
  1127. }
  1128.  
  1129. }
  1130.  
  1131. }
  1132. }
  1133. return dst;
  1134. }
  1135.  
  1136.  
  1137.  
  1138. Mat_<uchar> erosion(Mat_<uchar> src, Mat_<uchar> structure)
  1139. {
  1140. int rows = src.rows;
  1141. int cols = src.cols;
  1142. int width = structure.cols;
  1143. int height = structure.rows;
  1144. Mat_<uchar> dst(rows, cols, 255);
  1145. int di[8] = { -1, 0, 1, 0, -1, 1, 1, -1 };
  1146. int dj[8] = { 0, -1, 0, 1, -1, -1, 1, 1 };
  1147.  
  1148. for (int i = 0; i < rows; i++)
  1149. {
  1150. for (int j = 0; j < cols; j++)
  1151. {
  1152. if (src(i, j) == 0)
  1153. {
  1154. dst(i, j) = 0;
  1155. for (int m = -height / 2; m <= height / 2; m++)
  1156. {
  1157. for (int n = -width / 2; n <= width / 2; n++)
  1158. {
  1159. Point neighbor(j + n, i + m);
  1160. if (neighbor.x >= 0 && neighbor.x < cols && neighbor.y >= 0 && neighbor.y < rows)
  1161. {
  1162. if (structure(m + height / 2, n + width / 2) == 0 && src(neighbor) == 255)
  1163. {
  1164. dst(i, j) = 255;
  1165. }
  1166. }
  1167.  
  1168. }
  1169. }
  1170. }
  1171.  
  1172. }
  1173. }
  1174. return dst;
  1175. }
  1176.  
  1177.  
  1178.  
  1179. void testErosion()
  1180. {
  1181. char fname[MAX_PATH];
  1182. openFileDlg(fname);
  1183. Mat_<uchar> src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
  1184. Mat_<uchar> structure(3, 3);
  1185. structure(0, 0) = 255;
  1186. structure(0, 1) = 0;
  1187. structure(0, 2) = 255;
  1188. structure(1, 0) = 0;
  1189. structure(1, 1) = 0;
  1190. structure(1, 2) = 0;
  1191. structure(2, 0) = 255;
  1192. structure(2, 1) = 0;
  1193. structure(2, 2) = 255;
  1194. Mat_<uchar> dst = erosion(src, structure);
  1195.  
  1196. imshow("original", src);
  1197. imshow("eroded", dst);
  1198. waitKey(0);
  1199.  
  1200. }
  1201.  
  1202. void testDillation()
  1203. {
  1204. char fname[MAX_PATH];
  1205. openFileDlg(fname);
  1206. Mat_<uchar> src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
  1207. Mat_<uchar> structure(3, 3);
  1208. structure(0, 0) = 255;
  1209. structure(0, 1) = 0;
  1210. structure(0, 2) = 255;
  1211. structure(1, 0) = 0;
  1212. structure(1, 1) = 0;
  1213. structure(1, 2) = 0;
  1214. structure(2, 0) = 255;
  1215. structure(2, 1) = 0;
  1216. structure(2, 2) = 255;
  1217. Mat_<uchar> dst = dillation(src, structure);
  1218. imshow("original", src);
  1219. imshow("dillated", dst);
  1220. waitKey(0);
  1221. }
  1222.  
  1223.  
  1224. Mat_<uchar> opening(Mat_<uchar> src, Mat_<uchar> structure)
  1225. {
  1226. int rows = src.rows;
  1227. int cols = src.cols;
  1228. Mat_<uchar> dst(rows,cols);
  1229. Mat_<uchar> buffer = erosion(src, structure);
  1230. dst = dillation(buffer, structure);
  1231.  
  1232. return dst;
  1233. }
  1234.  
  1235. Mat_<uchar> closing(Mat_<uchar> src, Mat_<uchar> structure)
  1236. {
  1237. int rows = src.rows;
  1238. int cols = src.cols;
  1239. Mat_<uchar> dst(rows,cols);
  1240. Mat_<uchar> buffer = dillation(src, structure);
  1241. dst = erosion(buffer, structure);
  1242.  
  1243. return dst;
  1244. }
  1245.  
  1246. void testOpening()
  1247. {
  1248. char fname[MAX_PATH];
  1249. openFileDlg(fname);
  1250. Mat_<uchar> src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
  1251. Mat_<uchar> structure(3, 3);
  1252. structure(0, 0) = 255;
  1253. structure(0, 1) = 0;
  1254. structure(0, 2) = 255;
  1255. structure(1, 0) = 0;
  1256. structure(1, 1) = 0;
  1257. structure(1, 2) = 0;
  1258. structure(2, 0) = 255;
  1259. structure(2, 1) = 0;
  1260. structure(2, 2) = 255;
  1261. Mat_<uchar> dst = opening(src, structure);
  1262. imshow("original", src);
  1263. imshow("opened", dst);
  1264. waitKey(0);
  1265. }
  1266.  
  1267. void testClosing()
  1268. {
  1269. char fname[MAX_PATH];
  1270. openFileDlg(fname);
  1271. Mat_<uchar> src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
  1272. Mat_<uchar> structure(3, 3);
  1273. structure(0, 0) = 255;
  1274. structure(0, 1) = 0;
  1275. structure(0, 2) = 255;
  1276. structure(1, 0) = 0;
  1277. structure(1, 1) = 0;
  1278. structure(1, 2) = 0;
  1279. structure(2, 0) = 255;
  1280. structure(2, 1) = 0;
  1281. structure(2, 2) = 255;
  1282. Mat_<uchar> dst = closing(src, structure);
  1283. imshow("original", src);
  1284. imshow("closed", dst);
  1285. waitKey(0);
  1286. }
  1287.  
  1288. Mat_<uchar> difference(Mat_<uchar> A, Mat_<uchar> B)
  1289. {
  1290. int rows = A.rows;
  1291. int cols = A.cols;
  1292. Mat_<uchar> dst(rows, cols);
  1293. for (int i = 0; i < rows; i++)
  1294. {
  1295. for (int j = 0; j < cols; j++)
  1296. {
  1297. if (A(i, j) == B(i, j))
  1298. {
  1299. dst(i, j) = 255;
  1300. }
  1301. else
  1302. {
  1303. dst(i, j) = A(i, j);
  1304. }
  1305. }
  1306. }
  1307. return dst;
  1308.  
  1309. }
  1310.  
  1311. Mat_<uchar> boundaryExtraction(Mat_<uchar> src, Mat_<uchar> structure)
  1312. {
  1313. Mat_<uchar> eroded = erosion(src, structure);
  1314. Mat_<uchar> boundary = difference(src, eroded);
  1315. return boundary;
  1316.  
  1317. }
  1318.  
  1319. void testBoundaryExtraction()
  1320. {
  1321. char fname[MAX_PATH];
  1322. openFileDlg(fname);
  1323. Mat_<uchar> src = imread(fname, CV_LOAD_IMAGE_GRAYSCALE);
  1324. Mat_<uchar> dst(src.rows, src.cols);
  1325. Mat_<uchar> structure(3, 3);
  1326. structure(0, 0) = 0;
  1327. structure(0, 1) = 0;
  1328. structure(0, 2) = 0;
  1329. structure(1, 0) = 0;
  1330. structure(1, 1) = 0;
  1331. structure(1, 2) = 0;
  1332. structure(2, 0) = 0;
  1333. structure(2, 1) = 0;
  1334. structure(2, 2) = 0;
  1335. dst = boundaryExtraction(src, structure);
  1336.  
  1337. imshow("original", src);
  1338. imshow("boundary", dst);
  1339. waitKey(0);
  1340. }
  1341.  
  1342.  
  1343. int main()
  1344. {
  1345. int op;
  1346. do
  1347. {
  1348. system("cls");
  1349. destroyAllWindows();
  1350. printf("Menu:\n");
  1351. printf(" 1 - Open image\n");
  1352. printf(" 2 - Open BMP images from folder\n");
  1353. printf(" 3 - Image negative - diblook style\n");
  1354. printf(" 4 - BGR->HSV\n");
  1355. printf(" 5 - Resize image\n");
  1356. printf(" 6 - Canny edge detection\n");
  1357. printf(" 7 - Edges in a video sequence\n");
  1358. printf(" 8 - Snap frame from live video\n");
  1359. printf(" 9 - Mouse callback demo\n");
  1360. printf(" 10 - Lab2 Copy RGB\n");
  1361. printf(" 11 - Lab2 Convert to grayscale\n");
  1362. printf(" 12 - Lab2 Convert to binary\n");
  1363. printf(" 13 - Lab2 Compute HSV\n");
  1364. printf(" 14 - Lab4 Object properties\n");
  1365. printf(" 15 - Lab 3 show histogram\n");
  1366. printf(" 16 - Lab3 show bins histogram\n");
  1367. printf(" 17 - Lab3 multilevel thresholding\n");
  1368. printf(" 18 - Lab5 breadth first traversal\n");
  1369. printf(" 19- Lab5 label two pass\n");
  1370. printf(" 20- Lab6 border tracing\n");
  1371. printf(" 21 - Lab7 dillation\n");
  1372. printf(" 22 - Lab7 erosion\n");
  1373. printf(" 23 - Lab7 opening\n");
  1374. printf(" 24 - Lab7 closing\n");
  1375. printf(" 25 - Lab7 boundary extraction\n");
  1376. printf(" 0 - Exit\n\n");
  1377. printf("Option: ");
  1378. scanf("%d",&op);
  1379. switch (op)
  1380. {
  1381. case 1:
  1382. testOpenImage();
  1383. break;
  1384. case 2:
  1385. testOpenImagesFld();
  1386. break;
  1387. case 3:
  1388. testParcurgereSimplaDiblookStyle(); //diblook style
  1389. break;
  1390. case 4:
  1391. //testColor2Gray();
  1392. testBGR2HSV();
  1393. break;
  1394. case 5:
  1395. testResize();
  1396. break;
  1397. case 6:
  1398. testCanny();
  1399. break;
  1400. case 7:
  1401. testVideoSequence();
  1402. break;
  1403. case 8:
  1404. testSnap();
  1405. break;
  1406. case 9:
  1407. testMouseClick();
  1408. break;
  1409. case 10:
  1410. copy_RGB();
  1411. break;
  1412. case 11:
  1413. convert_to_grayscale();
  1414. break;
  1415. case 12:
  1416. convert_to_binary();
  1417. break;
  1418. case 13:
  1419. compute_HSV();
  1420. break;
  1421. case 14:
  1422. testMouseClick();
  1423. break;
  1424. case 15:
  1425. test_histogram();
  1426. break;
  1427. case 16:
  1428. test_bins_histogram();
  1429. break;
  1430. case 17:
  1431. testThresholding();
  1432. break;
  1433. case 18:
  1434. test_breadth_first_traversal();
  1435. break;
  1436. case 19:
  1437. test_label_two_pass();
  1438. break;
  1439. case 20:
  1440. testBorderTracing();
  1441. break;
  1442. case 21:
  1443. testDillation();
  1444. break;
  1445. case 22:
  1446. testErosion();
  1447. break;
  1448. case 23:
  1449. testOpening();
  1450. break;
  1451. case 24:
  1452. testClosing();
  1453. break;
  1454. case 25:
  1455. testBoundaryExtraction();
  1456. break;
  1457.  
  1458. }
  1459. }
  1460. while (op!=0);
  1461. return 0;
  1462. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement