-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWindowsProject.cpp
More file actions
1388 lines (1143 loc) · 47.8 KB
/
Copy pathWindowsProject.cpp
File metadata and controls
1388 lines (1143 loc) · 47.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// WindowsProject.cpp : Defines the entry point for the application.
//
#include "framework.h"
#include "WindowsProject.h"
#include <opencv2/core.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <filesystem> // C++17 standard header file name
#include <opencv2/features2d.hpp>
#include <opencv2/calib3d.hpp>
#include <iostream>
#include <windows.h> // For MessageBoxA (Win32)
#include <shlwapi.h> // For Win32 file system functions, if needed
#include <opencv2/opencv.hpp>
#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>
namespace fs = std::filesystem;
//////////////////
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <Windows.h>
#include <windef.h>
#include "atlbase.h"
#include "atlstr.h"
#include "comutil.h"
#include "commdlg.h"
#include <Wingdi.h>
#include <gdiplus.h>
#include <set>
//////////////////////
using namespace cv;
using namespace std;
#define MAX_LOADSTRING 100
OPENFILENAME ofn; // êîíñòðóêòîð çà ÷åòåíå/ïèñàíå íà ôàéë ïî èìå
char FileName[128]; //èìà íà âõîäíî èçîáðàæåíèå
char FileNameOut[128];//èìå íà èçõîäåí ôàéë
char path[128]; //äèðåêòîðèÿ íà âõîäíîòî èçîáðàæåíèå
char pathOut[128]; //äèðåòêòîðèÿ íà èçõîäåí ôàéë
char Title[128];
wchar_t szFilter[] = _TEXT("All Files(*.*)\0*.*\0\0");
// Global Variables:
HINSTANCE hInst; // current instance
WCHAR szTitle[MAX_LOADSTRING]; // The title bar text
WCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
HBITMAP hbmHBITMAP1 = NULL;// ìàíèïóëàòîð êúì âõîäíîòî èçîáðàæåíèå
LPBITMAPINFOHEADER m_lpBMIH1 = NULL;//çàãëàâàí ÷àñò íà âõîäíîòî èçîáðàæåíèå
BYTE* image1;// áàéòîâ ìàñèâ íà âõîäíîòî èçîáðàæåíèå
//potrebitelski promenlivi - za h-fajl
char* imname; //óêàçàòåë êúì èìå íà âõîäåí ôàéë
float width, height; //ðàçìåðè íà äúùåðåí ïðîçîðåö
Mat image; /// Ãëîáàëåí Mat îáåêò çà èçîáðàæåíèå
//ïðîìåíëèâè çà GDIPlus
GdiplusStartupInput gdiplusStartupInput;
ULONG_PTR gdiplusToken;
cv::Mat resizeImage(const cv::Mat& imageInput, int largestSizeDimension) {
// Resize the image while keeping the aspect ratio
cv::Mat resizedImage;
int targetSize = largestSizeDimension;
int width = imageInput.cols;
int height = imageInput.rows;
float aspectRatio = static_cast<float>(width) / height;
cv::Size newSize;
if (width > height) {
newSize = cv::Size(targetSize, static_cast<int>(targetSize / aspectRatio));
}
else {
newSize = cv::Size(static_cast<int>(targetSize * aspectRatio), targetSize);
}
cv::resize(imageInput, resizedImage, newSize);
return resizedImage;
}
cv::Mat preprocessImage(const cv::Mat& imageInput) {
// Check if the image is valid
if (imageInput.empty()) {
std::cerr << "Invalid image provided!" << std::endl;
return cv::Mat();
}
// Resize the image to a standard size for consistent processing
cv::Mat resizedImage = resizeImage(imageInput, 800);
// Convert the image to HSV color space
cv::Mat hsvImage;
cv::cvtColor(resizedImage, hsvImage, cv::COLOR_BGR2HSV);
// Mask the red color (lower and upper ranges)
cv::Mat redMask1, redMask2, redMask;
cv::inRange(hsvImage, cv::Scalar(0, 100, 100), cv::Scalar(10, 255, 255), redMask1); // Lower red
cv::inRange(hsvImage, cv::Scalar(160, 100, 100), cv::Scalar(180, 255, 255), redMask2); // Upper red
cv::bitwise_or(redMask1, redMask2, redMask); // Combine both masks
// Clean up the red mask using morphological operations
cv::Mat kernel = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(2, 2));
cv::morphologyEx(redMask, redMask, cv::MORPH_CLOSE, kernel); // Close small gaps
cv::morphologyEx(redMask, redMask, cv::MORPH_OPEN, kernel); // Remove noise
// Optional (Visualization for debugging)
cv::imshow("Red Mask", redMask);
cv::waitKey(1000); // Display for 1 second
return redMask;
}
std::vector<cv::Rect> detectStopSignContours(const cv::Mat& redMask, cv::Mat& debugImage) {
// Detect contours in the red mask
std::vector<std::vector<cv::Point>> contours;
cv::findContours(redMask, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
// Visualize all contours for debugging
cv::drawContours(debugImage, contours, -1, cv::Scalar(255, 0, 0), 2); // Draw contours in blue
// Filter contours by area and shape
std::vector<cv::Rect> candidateRegions;
for (const auto& contour : contours) {
double area = cv::contourArea(contour);
if (area < 1000) continue; // Ignore small contours
// Approximate the contour to a polygon
std::vector<cv::Point> approxContour;
cv::approxPolyDP(contour, approxContour, 0.02 * cv::arcLength(contour, true), true);
// Check if the contour has 6 to 10 sides
if (approxContour.size() >= 6 && approxContour.size() <= 10) {
// Store the bounding rectangle of the potential stop sign
candidateRegions.push_back(cv::boundingRect(approxContour));
}
}
return candidateRegions;
}
std::string performOCR(const cv::Mat& image) {
// Initialize tesseract OCR engine
tesseract::TessBaseAPI tess;
if (tess.Init("..\\..\\", "eng")) { // Initialize tesseract with English language
std::cerr << "Could not initialize tesseract!" << std::endl;
return "";
}
// Convert OpenCV image to grayscale for OCR
cv::Mat grayImage;
cv::cvtColor(image, grayImage, cv::COLOR_BGR2GRAY);
// Set the image for OCR
tess.SetImage(grayImage.data, grayImage.cols, grayImage.rows, 1, grayImage.cols);
// Perform OCR
std::string ocrResult = tess.GetUTF8Text();
return ocrResult;
}
void processStopSignImage(HWND hwnd, const cv::Mat& imageInput) {
cv::Mat resizedImage = resizeImage(imageInput, 800);
// Preprocess the image to extract red mask
cv::Mat redMask = preprocessImage(imageInput);
if (redMask.empty()) {
std::cerr << "Error processing image!" << std::endl;
return;
}
// Resize the input image to match the red mask size
cv::Mat debugImage = resizedImage.clone();
// Detect potential stop sign regions
std::vector<cv::Rect> detectedRegions = detectStopSignContours(redMask, debugImage);
// For each detected region, crop and perform OCR
for (const auto& rect : detectedRegions) {
// Crop the region of interest (ROI) from the resized image
cv::Mat roi = resizedImage(rect);
cv:Mat roiResized = resizeImage(roi, 200);
// In case of a strong perspective distortion it would be a good idea to perform homography (perspective transformation
// Perform OCR to detect text inside the stop sign region
std::string ocrText = performOCR(roiResized);
// Check if the OCR result contains the word "STOP" (case-insensitive)
std::string lowerOcrText = toLowerCase(ocrText); // Convert OCR result to lowercase
if (lowerOcrText.find("stop") != std::string::npos) { // Compare to lowercase "stop"
// Draw a green rectangle around the detected stop sign
cv::rectangle(resizedImage, rect, cv::Scalar(0, 255, 0), 2);
// Optionally, print OCR text for debugging
std::cout << "Detected STOP sign with OCR text: " << ocrText << std::endl;
}
}
// Display the results
imshow("Contours Detection", debugImage);
imshow("Stop Signs Detection", resizedImage);
cv::waitKey(0);
}
void recognizeNoEntrySign(HWND hWnd, const Mat& inputImage) {
// Resize the image
cv::Mat resizedImage = resizeImage(inputImage, 800);
// Convert to HSV color space
Mat hsvImage;
cvtColor(resizedImage, hsvImage, COLOR_BGR2HSV);
// Create a red mask
Mat mask1, mask2, redMask;
Scalar lowerRed1(0, 70, 50), upperRed1(10, 255, 255);
Scalar lowerRed2(170, 70, 50), upperRed2(180, 255, 255);
inRange(hsvImage, lowerRed1, upperRed1, mask1);
inRange(hsvImage, lowerRed2, upperRed2, mask2);
bitwise_or(mask1, mask2, redMask);
// Morphological operations to clean the mask
Mat kernel = getStructuringElement(MORPH_ELLIPSE, cv::Size(5, 5));
morphologyEx(redMask, redMask, MORPH_CLOSE, kernel);
// Show the red mask
imshow("Red Mask", redMask);
waitKey(0);
// Find contours in the red mask
vector<vector<cv::Point>> contours;
findContours(redMask, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// Debug: Draw contours on a separate image
Mat debugImage = resizedImage.clone();
cv::drawContours(debugImage, contours, -1, cv::Scalar(255, 0, 0), 2); // Draw contours in blue
// Proceed with detection logic
Mat outputImage = resizedImage.clone();
for (const auto& contour : contours) {
// Filter circular shapes
double area = contourArea(contour);
double perimeter = arcLength(contour, true);
if (perimeter == 0) continue;
std::vector<cv::Point> approx;
cv::approxPolyDP(contour, approx, 0.01 * perimeter, true);
// Additional check to improve accuracy
if (approx.size() == 8) {
continue;
}
double circularity = 4 * CV_PI * area / (perimeter * perimeter);
if (circularity > 0.7 && area > 500) { // Circularity threshold
// Get bounding box of the detected circle
cv::Rect boundingBox = boundingRect(contour);
Mat roi = resizedImage(boundingBox);
// Threshold for white regions inside the ROI
Mat roiHSV;
cvtColor(roi, roiHSV, COLOR_BGR2HSV);
Mat whiteMask;
inRange(roiHSV, Scalar(0, 0, 200), Scalar(180, 50, 255), whiteMask);
// Find contours in the white mask
vector<vector<cv::Point>> whiteContours;
findContours(whiteMask, whiteContours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
for (const auto& whiteContour : whiteContours) {
RotatedRect rect = minAreaRect(whiteContour);
Size2f size = rect.size;
if (size.width > size.height) {
// Draw a green rectangle around the no-entry sign
rectangle(outputImage, boundingBox, Scalar(0, 255, 0), 3);
}
}
}
}
// Display results
imshow("Contours Detection", debugImage);
imshow("No Entry Signs Detection", outputImage);
waitKey(0);
}
long Datasize(LPBITMAPINFOHEADER m_lpBMIH)
{//ïîìîùíà ôóíêöèÿ çà îïðåäåëÿíå íà ðàçìåðà íà ìàñèâà íà èçîáðàæåíèåòî
long sizeImage;
int p, dump;
p = 0;
if (m_lpBMIH->biBitCount == 8) p = 1;
if (m_lpBMIH->biBitCount == 24) p = 3;
dump = (m_lpBMIH->biWidth * p) % 4;
if (dump != 0) dump = 4 - dump;
sizeImage = m_lpBMIH->biHeight * (m_lpBMIH->biWidth + dump);
return sizeImage;
}
int Mask(int iSliderValue)
{ //ïîìîùíà ôóíêöèÿ çà îïðåäåëÿíå íà ðàçìåð íà ìàñêà ñëåä èçáîð ïî ðóëåð
int MaskSize;
if (iSliderValue < 4) MaskSize = 3; else
if (iSliderValue < 6) MaskSize = 5; else
if (iSliderValue < 8) MaskSize = 7; else
if (iSliderValue < 10) MaskSize = 9; else MaskSize = 11;
return MaskSize;
}
char* Uni2char(char* FileNameOut)
{ //ôóíêöèÿ çà òðàíñôîðìàöèÿ êúì Óíèêîä
char* imname0;
size_t origsize = wcslen((LPWSTR)FileNameOut) + 1;
size_t convertedChars = 0;
char strConcat[] = " (char *)";
size_t strConcatsize = (strlen(strConcat) + 1) * 2;
const size_t newsize = origsize * 2;
imname0 = new char[newsize + strConcatsize];
int errrr = wcstombs_s(&convertedChars, imname0, newsize, (LPWSTR)FileNameOut, _TRUNCATE);
if (errrr == 0) return imname0; else return 0;
}
void saveimage(HWND hWnd, Mat imResult)
{// ïîìîùíà ïðîöåäóðà çà çàïèñ íà ôàéë ñ ÷åòåíå íà èìå è ïðåîáðàçóâàíå â óíèêîä
char* imnameOut;
wchar_t defex[] = __TEXT("*.*");
*FileNameOut = 0;
RtlZeroMemory(&ofn, sizeof ofn);
ofn.lStructSize = sizeof ofn;
ofn.hwndOwner = hWnd;
ofn.hInstance = hInst;
ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT;
ofn.lpstrFilter = (LPWSTR)szFilter;
ofn.lpstrDefExt = (LPWSTR)defex;
ofn.lpstrCustomFilter = (LPWSTR)szFilter;
ofn.lpstrFile = (LPWSTR)FileNameOut;
ofn.nMaxFile = sizeof FileNameOut;
ofn.lpstrInitialDir = (LPCWSTR)pathOut;
if (GetSaveFileName(&ofn) != 0)
{
size_t origsize = wcslen((LPWSTR)FileNameOut) + 1;
size_t convertedChars = 0;
char strConcat[] = " (char*)";
size_t strConcatsize = (strlen(strConcat) + 1) * 2;
const size_t newsize = origsize * 2;
imnameOut = new char[newsize + strConcatsize];
int errrr = wcstombs_s(&convertedChars, imnameOut, newsize, (LPWSTR)FileNameOut, _TRUNCATE);
if (errrr == 0) imwrite(imnameOut, imResult);
delete[] imnameOut;
}
}
//
HBITMAP LoadFileImage(wchar_t* FileName); //ôóíêöèÿ çà çàðåæäàíå íà âúíøíî èçîáðàæåíèå
void getDataHBITMAP(HBITMAP hbmHBITMAP); //ïðîöåäóðà çà èçâëè÷àíå íà äàííèòå çà èçîáðàæåíèåòî
BOOL DisplayBmpJPG(HWND hWnd, HBITMAP hbmHBITMAP); //ôóíêöèÿ çà âèçóàëèçàöèÿ íà èçîáðàæåíèåòî â îñíîâíèÿ åêðàí
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
// Initialize global strings
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_WINDOWSPROJECT, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance(hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WINDOWSPROJECT));
MSG msg;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int)msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WINDOWSPROJECT));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_WINDOWSPROJECT);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // Store instance handle in our global variable
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case ID_RECOGNIZE_STOP_SIGN:
{
processStopSignImage(hWnd, image);
break;
}
case ID_RECOGNIZE_NO_ENTRY_SIGN:
{
recognizeNoEntrySign(hWnd, image);
break;
}
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
///////////////////////////////////
case ID_FILE_INPUTIMAGE32798:
{//çàðåæäàíå íà èçîáðàæåíèå ñëåä èçáîð íà èìå
wchar_t defex[] = __TEXT("*.*");
*FileName = 0;
RtlZeroMemory(&ofn, sizeof ofn);
ofn.lStructSize = sizeof ofn;
ofn.hwndOwner = hWnd;
ofn.hInstance = hInst;
ofn.lpstrFile = (LPWSTR)FileName;
ofn.nMaxFile = sizeof FileName;
ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST;
ofn.lpstrFilter = (LPWSTR)szFilter;
ofn.lpstrDefExt = (LPWSTR)defex;
ofn.lpstrCustomFilter = (LPWSTR)szFilter;
ofn.lpstrInitialDir = (LPCWSTR)path;
if (GetOpenFileName(&ofn) != 0)
{
size_t origsize = wcslen((LPWSTR)FileName) + 1;
size_t convertedChars = 0;
char strConcat[] = " (char *)";
size_t strConcatsize = (strlen(strConcat) + 1) * 2;
const size_t newsize = origsize * 2;
imname = new char[newsize + strConcatsize];
wcstombs_s(&convertedChars, imname, newsize, (LPWSTR)FileName, _TRUNCATE);
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
hbmHBITMAP1 = LoadFileImage((LPWSTR)FileName);
getDataHBITMAP(hbmHBITMAP1);
GdiplusShutdown(gdiplusToken);
image = imread(imname, 1);
delete[] imname;
}
else {}
}
break;
case ID_IMPROC_AVERAGE32776:
if (image.dims == 2) // ïðîâåðêà çà ïðåõâúðëåí ìàñèâ â Mat ìàñèâ
{
Mat imResult; //ìàñèâ çà ðåçóëòàòà îò îáðàáîòêàòà
namedWindow("Averaged", 0); //ãåíåðèðàíå íà ïðîçîðåö
resizeWindow("Averaged", int(width), int(height));//îãðàíè÷àâàíå íà ðàçìåðà íà ïðîçîðåöà
//Create trackbar to change masksize
int iSliderValue1 = 1;
createTrackbar("kernelSize", "Averaged", &iSliderValue1, 11);
while (true)
{
int MaskSize = Mask(iSliderValue1); //îïðåäåëÿíå íà ðàçìåðà íà ìàñêàòà
blur(image, imResult, Size2i(MaskSize, MaskSize));//ôèëòðàöèÿ
imshow("Averaged", imResult);//âèçóàëèçàöèÿ íà ðåóëòàò
int iKey = waitKey(50);
if ((iKey == 27) || (iKey == 119))
{
if (iKey == 119) //w
saveimage(hWnd, imResult);
if (iKey == 27) break;
}
}
}
break;
case ID_IMPROC_MEDIAN:
if (image.dims == 2)// ïðîâåðêà çà ïðåõâúðëåí ìàñèâ â Mat ìàñèâ
{
Mat imResult; // ìàñèâ çà ðåçóëòàòà îò îáðàáîòêàòà
namedWindow("Median", 0); // ãåíåðèðàíå íà ïðîçîðåö
resizeWindow("Median", int(width), int(height));//îãðàíè÷àâàíå íà ðàçìåðà íà ïðîçîðåöà
//Create trackbar to change kernelsize
int iSliderValue1 = 1;
createTrackbar("kernelSize", "Median", &iSliderValue1, 11);
while (true)
{
int MaskSize = Mask(iSliderValue1);//îïðåäåëÿíå íà ðàçìåðà íà ìàñêàòà
medianBlur(image, imResult, MaskSize); //ôèëòðàöèÿ
imshow("Median", imResult);//âèçóàëèçàöèÿ íà ðåóëòàò
int iKey = waitKey(50);
if ((iKey == 27) || (iKey == 119))
{
if (iKey == 119) //w
saveimage(hWnd, imResult);//çàïèñ íà ðåçóëòàòà
if (iKey == 27) break;
}
}
}
break;
case ID_IMPROC_GAUSS:
if (image.dims == 2) // ïðîâåðêà çà ïðåõâúðëåí ìàñèâ â Mat ìàñèâ
{
Mat imResult;// ìàñèâ çà ðåçóëòàòà îò îáðàáîòêàòà
//
namedWindow("GaussBlur", 0);// ãåíåðèðàíå íà ïðîçîðåö
resizeWindow("GaussBlur", int(width), int(height));//îãðàíè÷àâàíå íà ðàçìåðà íà ïðîçîðåöà
//Create trackbar to change brightness
int iSliderValue1 = 1;
createTrackbar("kernelSize", "GaussBlur", &iSliderValue1, 11);
while (true)
{
int MaskSize = Mask(iSliderValue1);//îïðåäåëÿíå íà ðàçìåðà íà ìàñêàòà
GaussianBlur(image, imResult, Size2i(MaskSize, MaskSize), 0, 0);//ôèëòðàöèÿ
imshow("GaussBlur", imResult);//âèçóàëèçàöèÿ íà ðåóëòàò
int iKey = waitKey(50);
if ((iKey == 27) || (iKey == 119))
{
if (iKey == 119) //w
saveimage(hWnd, imResult);//çàïèñ íà ðåçóëòàòà
if (iKey == 27) break;
}
}
}
break;
case ID_IMPROC_SOBEL:
if (image.dims == 2)// ïðîâåðêà çà ïðåõâúðëåí ìàñèâ â Mat ìàñèâ
{
Mat imResult;// ìàñèâ çà ðåçóëòàòà îò îáðàáîòêàòà
namedWindow("Sobel", 0);// ãåíåðèðàíå íà ïðîçîðåö
resizeWindow("Sobel", int(width), int(height));//îãðàíè÷àâàíå íà ðàçìåðà íà ïðîçîðåöà
int b = 1;
createTrackbar("scale", "Sobel", &b, 100);
while (true)
{
Sobel(image, imResult, image.depth(), 1, 1, 3, b, 0, BORDER_DEFAULT);//äèôåðåíöèðàíå
imshow("Sobel", imResult);//âèçóàëèçàöèÿ íà ðåóëòàò
int iKey = waitKey(50);
if ((iKey == 27) || (iKey == 119))
{
if (iKey == 119) //w
saveimage(hWnd, imResult);//çàïèñ íà ðåçóëòàòà
if (iKey == 27) break;
}
}
}
break;
case ID_IMPROC_LAPLAS:
if (image.dims == 2)// ïðîâåðêà çà ïðåõâúðëåí ìàñèâ â Mat ìàñèâ
{
Mat imResult;// ìàñèâ çà ðåçóëòàòà îò îáðàáîòêàòà
namedWindow("Laplacian", 0);// ãåíåðèðàíå íà ïðîçîðåö
resizeWindow("Laplacian", int(width), int(height));//îãðàíè÷àâàíå íà ðàçìåðà íà ïðîçîðåöà
int b = 1;
createTrackbar("scale", "Laplacian", &b, 100);
while (true)
{
Laplacian(image, imResult, image.depth(), 1, b, 0, BORDER_DEFAULT);//äèôåðåíöèðàíå
imshow("Laplacian", imResult);//âèçóàëèçàöèÿ íà ðåóëòàò
int iKey = waitKey(50);
if ((iKey == 27) || (iKey == 119))
{
if (iKey == 119) //w
saveimage(hWnd, imResult);//çàïèñ íà ðåçóëòàòà
if (iKey == 27) break;
}
}
}
break;
case ID_HISTOGRAMS_CALC:
if (image.dims == 2)// ïðîâåðêà çà ïðåõâúðëåí ìàñèâ â Mat ìàñèâ
{
int histSize = 256; //çàäàâàíå íà ðàçìåð íà ìàñèâà íà õèñòîãðàìàòà
Mat imResult; // áóôåðíî èçîáðàæåíèå
MatND Bh; //ìàñèâ çà ñàìàòà õèñòîãðàìà
image.copyTo(imResult);
namedWindow("Histogram", 0); // ãåíåðèðàíå íà ïðîçîðåö
int channels[] = { 0, 1, 2, 3 }; // äåôèíèðàíå íà êàíàëèòå çà 32-áèòîâî èçîáðàæåíèå
calcHist(&imResult, 1, channels, Mat(), Bh, 1, &histSize, 0); //ïðåñìÿòàíå íà õèñòîãðàìà çà ïúðâè êàíàë
Mat histImage = Mat::ones(200, 320, CV_8U) * 255; //îãðàíè÷àâàíå íà ìàòðèöà çà âèçóàëèçàöèÿ íà õèñòîãðàìàòà
normalize(Bh, Bh, 0, histImage.rows, NORM_MINMAX, CV_32F);//íîðìàëèçàöèÿ íà äàííèòå â õèñòîãðàìàòà
histImage = Scalar::all(255); //ïðåîáðàçóâàíâ â ñêàëàðíà ñòîéíîñò
int binW = cvRound((double)histImage.cols / histSize);//îïðåäåëÿíå íà ïîçèöèÿ çà âèçóàëèçàöèÿ
for (int i = 0; i < histSize; i++)
rectangle(histImage, Point2i(i * binW, histImage.rows),
Point2i((i + 1) * binW, histImage.rows - cvRound(Bh.at<float>(i))),
Scalar::all(0), -1, 8, 0);
imshow("Histogram", histImage);//âèçóàëèçàöèÿ íà õèñòîãðàìàòà
while (true)
{
int iKey = waitKey(50);
if ((iKey == 27) || (iKey == 119))
{
if (iKey == 119) //w
saveimage(hWnd, histImage);//çàïèñ íà õèñòîãðàìàòà
if (iKey == 27) break;
}
}
}
break;
case ID_HISTOGRAMS_EQUILIZE:
if (image.dims == 2) // ïðîâåðêà çà ïðåõâúðëåí ìàñèâ â Mat ìàñèâ
{
Mat imResult, img_hist_equalized; // ðàáîòíè ìàñèâè
cvtColor(image, imResult, COLOR_BGR2GRAY); //ïðåîáðàçóâàíå â ñèâî èçîáðàæåíèå
equalizeHist(imResult, img_hist_equalized);//åêâèëèçàöèÿ íà õèñòîãðàìàòà
namedWindow("Equilized image", 0);//ñúçäàâàíå íà ïðîçîðåö
resizeWindow("Equilized image", int(width), int(height));//îãðàíè÷àâàíå íà ïðîçîðåöà
imshow("Equilized image", img_hist_equalized);//âèçóàëèçàöèÿ íà ðåçóëòàòà
while (true)
{
int iKey = waitKey(50);
if ((iKey == 27) || (iKey == 119))
{
if (iKey == 119) //w
saveimage(hWnd, img_hist_equalized);//çàïèñ íà ðåçóëòàòà
if (iKey == 27) break;
}
}
}
break;
case ID_HISTOGRAMS_COMPARE:
if (image.dims == 2) // ïðîâåðêà çà ïðåõâúðëåí ìàñèâ â Mat ìàñèâ
{
Mat imResult; //ðàáîòåí ìàñèâ
image.copyTo(imResult);
//èçáîå íà èìå íà âòîðîòî èçîáðàæåíèå
char* imnameOut;
*FileNameOut = 0;
ofn.lpstrFile = (LPWSTR)FileNameOut;
ofn.nMaxFile = sizeof FileNameOut;
ofn.lpstrInitialDir = (LPCWSTR)pathOut;
if (GetOpenFileName(&ofn) == 0)
{
break;
}
else {
imnameOut = Uni2char(FileNameOut); //ïðåîáðàçóâàíå íà èìàòåî â óíèêîä
Mat secondIm; // ìàñèâ çà âòîðîòî èçîáðàæåíèå
secondIm = imread(imnameOut, 1);// çàðåæäàíå íà âòîðîòî èçèáðàæåíèå
namedWindow("Second Image", 0); //åêðàí çà âèçóàëèçàöèÿ íà âòîðîòî èçîáðàæåíèå
resizeWindow("Second Image", int(width), int(height));//îãðàíè÷àâàíå íà ðàçìåðà íà åêðàíà
//ïî ðàçìåðèòå íà ïúðâîòî èçîáðàæååíèå
imshow("Second Image", secondIm);//âèçóàëèçàöèÿ íà âòîðîòî èçîáðàæåíèå
delete imnameOut;
int histSize = 256; //îãðàíè÷àâàíå íà ðàçìåðà íà ìàñèâèòå íà õèñòîãðàìèòå
float ranges[] = { 0, 256 };
MatND hist1, hist2;//çàäàâàíå íà ìàñèâè çà õèñòîãðàìèòå
int channels[] = { 0, 1, 2, 3 };//äåôèíèðàíå íà êàíàëèòå
//ïðåñìÿòàíå íà õèñòîãðàìèòå ïî ïúðâèÿ êàíàë
calcHist(&imResult, 1, channels, Mat(), hist1, 1, &histSize, 0);
calcHist(&secondIm, 1, channels, Mat(), hist2, 1, &histSize, 0);
// èçáîð íà èìå íà ôàéë çà ñúõðàíÿâàíå íà èíôîðìàöèÿòà
errno_t err;
FILE* fstr;
*FileNameOut = 0;
ofn.lpstrFile = (LPWSTR)FileNameOut;
ofn.nMaxFile = sizeof FileNameOut;
ofn.lpstrInitialDir = (LPCWSTR)pathOut;
if (GetSaveFileName(&ofn) != 0)
{
char* imname = Uni2char(FileNameOut);
err = fopen_s(&fstr, imname, "w+");
if (err == 0)
{//ïðåñìÿòàíå íà êîåôèöèåíòèòå è çàïèñ íà ðåçóëòàòèòå
double self = compareHist(hist1, hist1, HISTCMP_CORREL);// CV_COMP_CORREL);
double comp = compareHist(hist1, hist2, HISTCMP_CORREL);// CV_COMP_CORREL);
fprintf_s(fstr, " Method Compare corell: self = %f comp= %f \n", self, comp);
self = compareHist(hist1, hist1, HISTCMP_CHISQR);// CV_COMP_CHISQR);
comp = compareHist(hist1, hist2, HISTCMP_CHISQR);// CV_COMP_CHISQR);
fprintf_s(fstr, " Method Compare chsqr: self = %f comp= %f \n", self, comp);
self = compareHist(hist1, hist1, HISTCMP_INTERSECT);// CV_COMP_INTERSECT);
comp = compareHist(hist1, hist2, HISTCMP_INTERSECT);// CV_COMP_INTERSECT);
fprintf_s(fstr, " Method Compare intersect: self = %f comp= %f \n", self, comp);
self = compareHist(hist1, hist1, HISTCMP_BHATTACHARYYA);// CV_COMP_BHATTACHARYYA);
comp = compareHist(hist1, hist2, HISTCMP_BHATTACHARYYA);// CV_COMP_BHATTACHARYYA);
fprintf_s(fstr, " Method Compare bhattacharyya: self = %f comp= %f \n", self, comp);
fclose(fstr);
delete imname;
}
}
}
}
break;
case ID_MORPHOLOGY_ERODE:
if (image.dims == 2)// ïðîâåðêà çà ïðåõâúðëåí ìàñèâ â Mat ìàñèâ
{
Mat imResult; // ðàáîòåí ìàñèâ çà ðåçóëòàòà îò îáðàáîòêàòà
image.copyTo(imResult);
namedWindow("Erode", 0); // ãåíåðèðàíå íà ïðîçîðåö
resizeWindow("Erode", int(width), int(height));//îãðàíè÷àâàíå íà ðàçìåðà íà ïðîçîðåöà
//çàäàâàíå íà ñòðóêòóðåí åëåìåíò
Mat element = getStructuringElement(MORPH_RECT, Size2i(3, 3), Point2i(1, 1));
erode(image, imResult, element);//åðîçèÿ
imshow("Erode", imResult);//âèçóàëèçàöèÿ íà ðåçóëòàòà
while (true)
{
int iKey = waitKey(50);
if ((iKey == 27) || (iKey == 119))
{
if (iKey == 119) //w
saveimage(hWnd, imResult);//çàïèñ íà ðåçóëòàòà
if (iKey == 27) break;
}
}
}
break;
case ID_MORPHOLOGY_DILATE:
if (image.dims == 2)// ïðîâåðêà çà ïðåõâúðëåí ìàñèâ â Mat ìàñèâ
{
Mat imResult;// ìàñèâ çà ðåçóëòàòà îò îáðàáîòêàòà
image.copyTo(imResult);
namedWindow("Dilate", 0);// ãåíåðèðàíå íà ïðîçîðåö
resizeWindow("Dilate", int(width), int(height));//îãðàíè÷àâàíå íà ðàçìåðà íà ïðîçîðåöà
//çàäàâàíå íà ñòðóêòóðåí åëåìåíò
Mat element = getStructuringElement(MORPH_RECT, Size2i(3, 3), Point2i(1, 1));
dilate(image, imResult, element);//äèëàòàöèÿ
imshow("Dilate", imResult);//âèçóàëèçàöèÿ íà ðåçóëòàòà
while (true)
{
int iKey = waitKey(50);
if ((iKey == 27) || (iKey == 119))
{
if (iKey == 119) //w
saveimage(hWnd, imResult);//çàïèñ íà ðåçóëòàòà
if (iKey == 27) break;
}
}
}
break;
case ID_MORPHOLOGY_OPEN:
if (image.dims == 2) // ïðîâåðêà çà ïðåõâúðëåí ìàñèâ â Mat ìàñèâ
{
Mat imResult;// ðàáîòåí ìàñèâ çà ðåçóëòàòà îò îáðàáîòêàòà
image.copyTo(imResult);
namedWindow("Open", 0);// ãåíåðèðàíå íà ïðîçîðåö
resizeWindow("Open", int(width), int(height));//îãðàíè÷àâàíå íà ðàçìåðà íà ïðîçîðåöà
//çàäàâàíå íà ñòðóêòóðåí åëåìåíò
Mat element = getStructuringElement(MORPH_RECT, Size2i(3, 3), Point2i(1, 1));
morphologyEx(image, imResult, MORPH_OPEN, element);// îïåðàöèÿ "îòâàðÿíå"
imshow("Open", imResult);
while (true)
{
int iKey = waitKey(50);
if ((iKey == 27) || (iKey == 119))
{
if (iKey == 119) //w
saveimage(hWnd, imResult);// âèçóàëèçàöèÿ íà ðåçóëòàòà
if (iKey == 27) break;
}
}
}
break;
case ID_MORPHOLOGY_CLOSE:
if (image.dims == 2) // ïðîâåðêà çà ïðåõâúðëåí ìàñèâ â Mat ìàñèâ
{
Mat imResult;// ðàáîòåí ìàñèâ çà ðåçóëòàòà îò îáðàáîòêàòà
image.copyTo(imResult);
namedWindow("Close", 0);// ãåíåðèðàíå íà ïðîçîðåö
resizeWindow("Close", int(width), int(height));//îãðàíè÷àâàíå íà ðàçìåðà íà ïðîçîðåöà
//çàäàâàíå íà ñòðóêòóðåí åëåìåíò
Mat element = getStructuringElement(MORPH_RECT, Size2i(3, 3), Point2i(1, 1));
morphologyEx(image, imResult, MORPH_CLOSE, element);// îïðåàöèÿ ïî çàòâàðÿíå
imshow("Close", imResult);// âèçóàëèçàöèÿ íà ðåçóëòàòà
while (true)
{
int iKey = waitKey(50);
if ((iKey == 27) || (iKey == 119))
{
if (iKey == 119) //w
saveimage(hWnd, imResult);// âèçóàëèçàöèÿ íà ðåçóëòàòà
if (iKey == 27) break;
}
}
}
break;
case ID_TRANSPORMS_MAKEBINARY:
if (image.dims == 2) // ïðîâåðêà çà ïðåõâúðëåí ìàñèâ â Mat ìàñèâ
{
Mat imGrayScale, imResult;// ðàáîòíè ìàñèâè
image.copyTo(imResult);
cvtColor(imResult, imGrayScale, COLOR_RGB2GRAY);//ïðåîáðàçóâàíå â ñèâî èçîáðàæåíèå
namedWindow("Binary", 0);// ãåíåðèðàíå íà ïðîçîðåö
resizeWindow("Binary", int(width), int(height));//îãðàíè÷àâàíå íà ðàçìåðà íà ïðîçîðåöà
//thresholding the grayscale image to get better results
int treshold = 127;
createTrackbar("treshold", "Binary", &treshold, 254);// ãåíåðèðàíå íà ðóëåð çà ïðàã
while (true)
{
threshold(imGrayScale, imResult, treshold, 255, THRESH_BINARY);// áèíàðèçàöèÿ
imshow("Binary", imResult);// âèçóàëèçàöèÿ íà ðåçóëòàòà
int iKey = waitKey(50);
if ((iKey == 27) || (iKey == 119))
{
if (iKey == 119) //w
saveimage(hWnd, imResult);// çàïèñ íà ðåçóëòàòà
if (iKey == 27) break;
}
}
}
break;
case ID_TRANSPORMS_MAKEGRAY:
if (image.dims == 2) // ïðîâåðêà çà ïðåõâúðëåí ìàñèâ â Mat ìàñèâ
{
Mat gray_image; // ðàáîòåí ìàñèâ çà ðåçóëòàòà îò îáðàáîòêàòà
cvtColor(image, gray_image, COLOR_RGB2GRAY);//ïðåîáðàçóâàíå â ñèâî èçîáðàæåíèå
namedWindow("Gray image", 0);// ãåíåðèðàíå íà ïðîçîðåö
resizeWindow("Gray image", int(width), int(height));//îãðàíè÷àâàíå íà ðàçìåðà íà ïðîçîðåöà
imshow("Gray image", gray_image);//âèçóàëèçàöèÿ íà ðåçóëòàòà
while (true)
{
int iKey = waitKey(50);
if ((iKey == 27) || (iKey == 119))
{
if (iKey == 119) //w
saveimage(hWnd, gray_image);//çàïèñ íà ðåçóëòàòà
if (iKey == 27) break;
}
}
}
break;
case ID_TRANSPORMS_FOURIER:
if (image.dims == 2) // ïðîâåðêà çà ïðåõâúðëåí ìàñèâ â Mat ìàñèâ
{
Mat gray_image; // ðàáîòåí ìàñèâ çà ðåçóëòàòà îò îáðàáîòêàòà
cvtColor(image, gray_image, COLOR_RGB2GRAY);//ïðåîáðàçóâàíå â ñèâî èçîáðàæåíèå