-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
1677 lines (1529 loc) · 71.9 KB
/
main.cpp
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
/*
#include <opencv2/opencv.hpp>
// Callback function for the trackbar
void onTrackbar(int value, void* userData) {
cv::Mat* frame = static_cast<cv::Mat*>(userData);
cv::Mat gray;
cv::cvtColor(*frame, gray, cv::COLOR_BGR2GRAY); // Convert to grayscale
cv::Mat binary;
cv::threshold(gray, binary, value, 255, cv::THRESH_BINARY); // Apply threshold
// Find contours in the binary image
std::vector<std::vector<cv::Point>> contours;
cv::findContours(binary, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
// Filter contours to find the most likely rectangle
double maxArea = 0;
std::vector<cv::Point> maxContour;
for (const auto& contour : contours) {
double area = cv::contourArea(contour);
if (area > maxArea) {
maxArea = area;
maxContour = contour;
}
}
// If a contour with a significant area is found
if (!maxContour.empty()) {
// Approximate the contour to a polygon
std::vector<cv::Point> approx;
cv::approxPolyDP(maxContour, approx, 0.04 * cv::arcLength(maxContour, true), true);
// If the polygon has four corners, it is likely a rectangle
if (approx.size() == 4) {
// Draw the rectangle and its sides
cv::Mat coloredBinary;
cv::cvtColor(binary, coloredBinary, cv::COLOR_GRAY2BGR); // Convert binary to color
cv::drawContours(
, std::vector<std::vector<cv::Point>>{approx}, -1, cv::Scalar(0, 255, 0), 2);
for (int i = 0; i < 4; ++i) {
cv::line(coloredBinary, approx[i], approx[(i + 1) % 4], cv::Scalar(0, 255, 0), 2);
}
// Resize the perfect rectangle before displaying it
// Calculate the scaling factor
double scale = 300.0 / coloredBinary.cols;
cv::resize(coloredBinary, coloredBinary, cv::Size(), scale, scale);
cv::imshow("Camera", coloredBinary);
// Transform the rectangle into a perfect rectangle
cv::Point2f srcPoints[4];
float rect_width = 1100.0;
float rect_height = 900.0;
cv::Point2f dstPoints[4] = {{0, 0}, {0, rect_height}, {rect_width, rect_height}, {rect_width, 0}}; // Define the destination points for the perfect rectangle
for (int i = 0; i < 4; ++i) {
srcPoints[i] = approx[i];
}
cv::Mat transformMatrix = cv::getPerspectiveTransform(srcPoints, dstPoints);
cv::Mat perfectRect;
cv::warpPerspective(binary, perfectRect, transformMatrix, cv::Size(rect_width, rect_height));
// Crop the perfect rectangle to cut the border
int borderSize = 10;
cv::Rect roi(borderSize, borderSize, perfectRect.cols - 2 * borderSize, perfectRect.rows - 2 * borderSize);
cv::Mat croppedRect = perfectRect(roi);
// Dilate the cropped rectangle to expand black areas
cv::Mat dil_element = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(20, 20)); // Define dilation kernel
cv::Mat dilatedRect;
cv::dilate(croppedRect, dilatedRect, dil_element); // 'element' is the erosion kernel from the previous code snippet
// Erode the black areas
cv::Mat element = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(35, 35)); // Define erosion kernel
cv::Mat erodedRect;
cv::erode(dilatedRect, erodedRect, element);
cv::erode(erodedRect, erodedRect, element);
// Convert erodedRect to BGR for displaying circles in color
cv::Mat erodedRectBGR;
cv::cvtColor(erodedRect, erodedRectBGR, cv::COLOR_GRAY2BGR);
// Find circles in the erodedRect
std::vector<cv::Vec3f> circles;
cv::HoughCircles(erodedRect, circles, cv::HOUGH_GRADIENT, 1,
100.0, // change this value to detect circles with different distances to each other
100, 30, 80, 700 // change the last two parameters
// (min_radius & max_radius) to detect larger circles
);
// Draw the circles
for (size_t i = 0; i < circles.size(); i++) {
cv::Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
// Draw the circle center
cv::circle(erodedRectBGR, center, 3, cv::Scalar(0, 255, 0), -1, 8, 0);
// Draw the circle outline
cv::circle(erodedRectBGR, center, radius, cv::Scalar(0, 0, 255), 3, 8, 0);
}
cv::imshow("Perfect Rectangle", erodedRectBGR);
return;
}
}
// If no rectangle is found, show the binary image without modifications
// Resize the perfect rectangle before displaying it
// Calculate the scaling factor
double scale = 300.0 / binary.cols;
cv::resize(binary, binary, cv::Size(), scale, scale);
cv::imshow("Camera", binary);
}
int main() {
cv::VideoCapture cap(0); // Open the default camera
if (!cap.isOpened()) {
std::cerr << "Error: Unable to open the camera" << std::endl;
return -1;
}
cv::Mat frame; // Placeholder for the current frame
cap.read(frame); // Read a frame from the camera
cv::namedWindow("Camera");
int initialThreshold = 184; // Initial threshold value
int maxThreshold = 255; // Maximum threshold value
cv::createTrackbar("Threshold", "Camera", &initialThreshold, maxThreshold, onTrackbar, &frame);
onTrackbar(initialThreshold, &frame); // Initial binary conversion
while (true) {
cap.read(frame); // Read a frame from the camera
if (frame.empty()) {
std::cerr << "Error: Unable to read frame from the camera" << std::endl;
break;
}
int key = cv::waitKey(30);
if (key == 27) // Break the loop if 'Esc' is pressed
break;
onTrackbar(initialThreshold, &frame);
}
cap.release(); // Release the camera
cv::destroyAllWindows(); // Close all OpenCV windows
return 0;
}
*/
/*
#include <opencv2/opencv.hpp>
#include <deque>
// Structure to store the detected circle
struct DetectedCircle {
cv::Point center;
int radius;
};
// Callback function for the trackbar
void onTrackbar(int value, void* userData) {
cv::Mat* frame = static_cast<cv::Mat*>(userData);
cv::Mat gray;
cv::cvtColor(*frame, gray, cv::COLOR_BGR2GRAY); // Convert to grayscale
cv::Mat binary;
cv::threshold(gray, binary, value, 255, cv::THRESH_BINARY); // Apply threshold
// Find contours in the binary image
std::vector<std::vector<cv::Point>> contours;
cv::findContours(binary, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
// Filter contours to find the most likely rectangle
double maxArea = 0;
std::vector<cv::Point> maxContour;
for (const auto& contour : contours) {
double area = cv::contourArea(contour);
if (area > maxArea) {
maxArea = area;
maxContour = contour;
}
}
// If a contour with a significant area is found
if (!maxContour.empty()) {
// Approximate the contour to a polygon
std::vector<cv::Point> approx;
cv::approxPolyDP(maxContour, approx, 0.04 * cv::arcLength(maxContour, true), true);
// If the polygon has four corners, it is likely a rectangle
if (approx.size() == 4) {
// Draw the rectangle and its sides
cv::Mat coloredBinary;
cv::cvtColor(binary, coloredBinary, cv::COLOR_GRAY2BGR); // Convert binary to color
cv::drawContours(coloredBinary, std::vector<std::vector<cv::Point>>{approx}, -1, cv::Scalar(0, 255, 0), 2);
for (int i = 0; i < 4; ++i) {
cv::line(coloredBinary, approx[i], approx[(i + 1) % 4], cv::Scalar(0, 255, 0), 2);
}
// Resize the perfect rectangle before displaying it
// Calculate the scaling factor
double scale = 300.0 / coloredBinary.cols;
cv::resize(coloredBinary, coloredBinary, cv::Size(), scale, scale);
cv::imshow("Camera", coloredBinary);
// Transform the rectangle into a perfect rectangle
cv::Point2f srcPoints[4];
float rect_width = 1100.0;
float rect_height = 900.0;
cv::Point2f dstPoints[4] = {{0, 0}, {0, rect_height}, {rect_width, rect_height}, {rect_width, 0}}; // Define the destination points for the perfect rectangle
for (int i = 0; i < 4; ++i) {
srcPoints[i] = approx[i];
}
cv::Mat transformMatrix = cv::getPerspectiveTransform(srcPoints, dstPoints);
cv::Mat perfectRect;
cv::warpPerspective(binary, perfectRect, transformMatrix, cv::Size(rect_width, rect_height));
// Crop the perfect rectangle to cut the border
int borderSize = 10;
cv::Rect roi(borderSize, borderSize, perfectRect.cols - 2 * borderSize, perfectRect.rows - 2 * borderSize);
cv::Mat croppedRect = perfectRect(roi);
// Dilate the cropped rectangle to expand black areas
cv::Mat dil_element = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(20, 20)); // Define dilation kernel
cv::Mat dilatedRect;
cv::dilate(croppedRect, dilatedRect, dil_element); // 'element' is the erosion kernel from the previous code snippet
// Erode the black areas
cv::Mat element = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(35, 35)); // Define erosion kernel
cv::Mat erodedRect;
cv::erode(dilatedRect, erodedRect, element);
cv::erode(erodedRect, erodedRect, element);
// Convert erodedRect to BGR for displaying circles in color
cv::Mat erodedRectBGR;
cv::cvtColor(erodedRect, erodedRectBGR, cv::COLOR_GRAY2BGR);
// Find circles in the erodedRect
std::vector<cv::Vec3f> circles;
cv::HoughCircles(erodedRect, circles, cv::HOUGH_GRADIENT, 1,
100.0, // change this value to detect circles with different distances to each other
100, 30, 80, 700 // change the last two parameters
// (min_radius & max_radius) to detect larger circles
);
// Store the detected circles for this frame
std::deque<DetectedCircle> prevCircles;
for (const auto& circle : circles) {
prevCircles.push_back({cv::Point(cvRound(circle[0]), cvRound(circle[1])), cvRound(circle[2])});
}
// Draw the average circle from the previous frames
cv::Point avgCenter(0, 0);
int avgRadius = 0;
int count = 0;
for (const auto& circle : prevCircles) {
if (circle.radius > 0) {
avgCenter += circle.center;
avgRadius += circle.radius;
count++;
}
}
if (count > 0) {
avgCenter.x /= count;
avgCenter.y /= count;
avgRadius /= count;
cv::circle(erodedRectBGR, avgCenter, avgRadius, cv::Scalar(255, 0, 0), 2);
}
// Draw the circles detected in the current frame
for (const auto& circle : circles) {
cv::Point center(cvRound(circle[0]), cvRound(circle[1]));
int radius = cvRound(circle[2]);
// Draw the circle center
// cv::circle(erodedRectBGR, center, 3, cv::Scalar(0, 255, 0), -1, 8, 0);
// // Draw the circle outline
// cv::circle(erodedRectBGR, center, radius, cv::Scalar(0, 0, 255), 3, 8, 0);
}
cv::imshow("Perfect Rectangle", erodedRectBGR);
}
}
// If no rectangle is found, show the binary image without modifications
// Resize the perfect rectangle before displaying it
// Calculate the scaling factor
double scale = 300.0 / binary.cols;
cv::resize(binary, binary, cv::Size(), scale, scale);
cv::imshow("Camera", binary);
}
int main() {
cv::VideoCapture cap(0); // Open the default camera
if (!cap.isOpened()) {
std::cerr << "Error: Unable to open the camera" << std::endl;
return -1;
}
cv::Mat frame; // Placeholder for the current frame
cap.read(frame); // Read a frame from the camera
cv::namedWindow("Camera");
int initialThreshold = 200; // Initial threshold value
int maxThreshold = 255; // Maximum threshold value
cv::createTrackbar("Threshold", "Camera", &initialThreshold, maxThreshold, onTrackbar, &frame);
onTrackbar(initialThreshold, &frame); // Initial binary conversion
while (true) {
cap.read(frame); // Read a frame from the camera
if (frame.empty()) {
std::cerr << "Error: Unable to read frame from the camera" << std::endl;
break;
}
int key = cv::waitKey(30);
if (key == 27) // Break the loop if 'Esc' is pressed
break;
onTrackbar(initialThreshold, &frame);
}
cap.release(); // Release the camera
cv::destroyAllWindows(); // Close all OpenCV windows
return 0;
}
*/
/*
#include <cstdio>
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/optional_debug_tools.h"
// This is an example that is minimal to read a model
// from disk and perform inference. There is no data being loaded
// that is up to you to add as a user.
//
// NOTE: Do not add any dependencies to this that cannot be built with
// the minimal makefile. This example must remain trivial to build with
// the minimal build tool.
//
// Usage: minimal <tflite model>
#define TFLITE_MINIMAL_CHECK(x) \
if (!(x)) { \
fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); \
exit(1); \
}
int main(int argc, char* argv[]) {
if (argc != 2) {
fprintf(stderr, "minimal <tflite model>\n");
return 1;
}
const char* filename = argv[1];
// Load model
std::unique_ptr<tflite::FlatBufferModel> model =
tflite::FlatBufferModel::BuildFromFile(filename);
TFLITE_MINIMAL_CHECK(model != nullptr);
// Build the interpreter with the InterpreterBuilder.
// Note: all Interpreters should be built with the InterpreterBuilder,
// which allocates memory for the Interpreter and does various set up
// tasks so that the Interpreter can read the provided model.
tflite::ops::builtin::BuiltinOpResolver resolver;
tflite::InterpreterBuilder builder(*model, resolver);
std::unique_ptr<tflite::Interpreter> interpreter;
builder(&interpreter);
TFLITE_MINIMAL_CHECK(interpreter != nullptr);
// Allocate tensor buffers.
TFLITE_MINIMAL_CHECK(interpreter->AllocateTensors() == kTfLiteOk);
printf("=== Pre-invoke Interpreter State ===\n");
tflite::PrintInterpreterState(interpreter.get());
// Fill input buffers
// TODO(user): Insert code to fill input tensors.
// Note: The buffer of the input tensor with index `i` of type T can
// be accessed with `T* input = interpreter->typed_input_tensor<T>(i);`
// Run inference
TFLITE_MINIMAL_CHECK(interpreter->Invoke() == kTfLiteOk);
printf("\n\n=== Post-invoke Interpreter State ===\n");
tflite::PrintInterpreterState(interpreter.get());
// Read output buffers
// TODO(user): Insert getting data out code.
// Note: The buffer of the output tensor with index `i` of type T can
// be accessed with `T* output = interpreter->typed_output_tensor<T>(i);`
return 0;
}
*/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <opencv2/opencv.hpp>
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/string_util.h"
#include "tensorflow/lite/examples/label_image/get_top_n.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/optional_debug_tools.h"
#include <filesystem>
#include <cmath>
#include <sstream>
#include <signal.h>
#include <sys/time.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <math.h>
#include <pthread.h>
#include <time.h>
#define DID 22 // Device ID (fixed)
#define DEV 100 // The Number of Devices
#define SCE 100 // The number of Scenarios
#define GAM 100 // The number of Games
int DeviceValid[DEV+1], // available devices
GameValid[GAM+1], // available games
ScenarioValid[SCE+1]; // available scenarios
// UDP to get the Server IP Address - - - - - -
#define BUFSIZE 8192
#define ISS_UDP_PORT 9000 // Port ID for UDP/IP ISS Database communication
#define ISS_TCP_PORT 9866 // ISS Database Server
#define ISS_UDPR_PORT 9868 // Port ID for UDP/IP ISS Database Receiver communication
#define TIMEOUT_MS 5000 // milliSeconds between retransmits
char ISS_ServerIP[30]="192.168.13.100",
buf[BUFSIZE];
int fin2=0, // 1: game end (ready to start)
GameScore[GAM+1],
DeviceID=DID, // Device ID (000-999)
ISSstate=-1, // 0: not connected, 1: connected
DeviceStage=0, // state to send to the ISS server
DeviceCommand=0, // DeviceCommand to send to the ISS server
DeviceData=0, // state or value to send to the ISS server
DataSent=1, // 0: ready to send, 1: sent
ScenarioStage=0, // Scenario Stage
ScenarioValue, // Scenario Value (data)
ScenarioStartTime; // Secnario Starting Time in Sec (00-59)
int ISS_UDP_receive() // receive server (host) IP through UDP/IP ISS Database communication
{
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 100000;
int i=0,sock;
struct sockaddr_in addr;
sock = socket(AF_INET, SOCK_DGRAM, 0);
addr.sin_family = AF_INET;
addr.sin_port = htons(ISS_UDP_PORT);
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_len = sizeof(addr);
bind(sock, (struct sockaddr *)&addr, sizeof(addr));
memset(ISS_ServerIP, 0, sizeof(ISS_ServerIP));
recv(sock, ISS_ServerIP, sizeof(ISS_ServerIP), 0);
printf("ISS Database Server IP %s\n", ISS_ServerIP);
close(sock);
return(i);
}
void init() // init for each scenario
{
int i;
fin2=1; // game end (ready to start)
DataSent=1;
DeviceID=DID;
DeviceStage=ScenarioStage;
DeviceCommand=0;
DeviceData=0;
for (i=0; i<DEV; i++)
DeviceValid[i]=-1; // available devices
for (i=0; i<GAM; i++)
GameValid[i]=-1; // available games
for (i=0; i<SCE; i++)
ScenarioValid[i]=-1; // available scenarios
// printf("\n\n Data init is done. \n\n");
}
void senddata(){ // send state / DeviceCommand and data to the server
char sentdata[BUFSIZE],
codeno[BUFSIZE]; // text to int
struct sockaddr_in server;
unsigned long dst_ip = inet_addr(ISS_ServerIP);
int port = ISS_TCP_PORT; // database server
int h, // ID
i,j,k,s;
char numberName[20]="01234567890";
memset(sentdata, 0, sizeof(sentdata));
if (DeviceID>=100){
k=(int)(DeviceID/100)%10;
sentdata[0]=numberName[k]; // Device ID (000-999)
}
else
sentdata[0]=numberName[0];
if (DeviceID>=10){
k=(int)(DeviceID/10)%10;
sentdata[1]=numberName[k];
}
else
sentdata[1]=numberName[0];
k=DeviceID%10;
sentdata[2]=numberName[k];
if (DeviceStage>=1000) {
k=(int)(DeviceStage/1000)%10;
sentdata[3]=numberName[k]; // State / stage ID (0000 - 9999)
}
else
sentdata[3]=numberName[0];
if (DeviceStage>=100) {
k=(int)(DeviceStage/100)%10;
sentdata[4]=numberName[k];
}
else
sentdata[4]=numberName[0];
if (DeviceStage>=10) {
k=(int)(DeviceStage/10)%10;
sentdata[5]=numberName[k];
}
else
sentdata[5]=numberName[0];
k=DeviceStage%10;
sentdata[6]=numberName[k];
if (DeviceCommand>=10) { // send DeviceCommand data (00 - 99)
k=(int)(DeviceCommand/10)%10;
sentdata[7]=numberName[k]; // value ID
}
else
sentdata[7]=numberName[0]; // value ID
k=DeviceCommand%10;
sentdata[8]=numberName[k]; // value ID
if (DeviceData>=10) { // send value (00 - 99)
k=(int)(DeviceData/10)%10;
sentdata[9]=numberName[k]; // value ID
}
else
sentdata[9]=numberName[0]; // value ID
k=DeviceData%10;
sentdata[10]=numberName[k]; // value ID
if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("Fail to ISS Server\n");
}
else{
memset((char *) &server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = dst_ip;
server.sin_port = htons(port);
if (connect(s, (struct sockaddr *) &server, sizeof server) < 0) {
printf(" Device [%d] No ISS Server - State:%d\n",
DeviceID, DeviceStage);
ISSstate=0;
}
else{
write(s, sentdata, strlen(sentdata)); // sending data
memset(buf, 0, sizeof(buf));
read(s, buf, sizeof(buf)); // receiving data
close(s);
ISSstate=1;
memset(codeno, 0, sizeof(codeno));
codeno[0]=buf[0]; // Device State
codeno[1]=buf[1]; // Device State
codeno[2]=buf[2]; // Device State
codeno[3]=buf[3]; // Device State
ScenarioStage=atoi(codeno); // Scenario State:
memset(codeno, 0, sizeof(codeno));
codeno[0]=buf[4]; // Device Value
codeno[1]=buf[5]; // Device Value
codeno[2]=buf[6]; // Device Value
codeno[3]=buf[7]; // Device Value
if ((ScenarioStage == 2)&&(ScenarioStage != DeviceStage))
init();
else if (ScenarioStage == 3){
ScenarioStartTime=atoi(codeno); // Starting Time in Sec (00-59)
}
else if (DeviceCommand == 15){
memset(codeno, 0, sizeof(codeno));
codeno[0]=buf[4]; // Scenario ID
codeno[1]=buf[5];
h=atoi(codeno); // Scenario ID
memset(codeno, 0, sizeof(codeno));
codeno[0]=buf[6]; // Scenario Valid
codeno[1]=buf[7];
ScenarioValid[h]=atoi(codeno); // Scenario Valid
printf("- - The previous Game [%d] Score: %d\n",
h,ScenarioValid[h]);
}
else if (DeviceCommand == 16){
memset(codeno, 0, sizeof(codeno));
codeno[0]=buf[4]; // Scenario ID
codeno[1]=buf[5];
h=atoi(codeno); // Scenario ID
memset(codeno, 0, sizeof(codeno));
codeno[0]=buf[6]; // Scenario Valid
codeno[1]=buf[7];
ScenarioValid[h]=atoi(codeno); // Scenario Valid
printf("- - Total Scenario [%d] Score: %d\n",
h,ScenarioValid[h]);
}
else if (DeviceCommand == 20){
memset(codeno, 0, sizeof(codeno));
codeno[0]=buf[4]; // Scenario ID
codeno[1]=buf[5];
h=atoi(codeno); // Scenario ID
memset(codeno, 0, sizeof(codeno));
codeno[0]=buf[6]; // Scenario Valid
codeno[1]=buf[7];
ScenarioValid[h]=atoi(codeno); // Scenario Valid
printf("Scenario[%d] avaialble: %d\n",
h,ScenarioValid[h]);
}
else if (DeviceCommand == 21){
memset(codeno, 0, sizeof(codeno));
codeno[0]=buf[4]; // Game ID
codeno[1]=buf[5];
h=atoi(codeno); // Game ID
memset(codeno, 0, sizeof(codeno));
codeno[0]=buf[6]; // Game Valid
codeno[1]=buf[7];
GameValid[h]=atoi(codeno); // Scenario Valid
printf("Game[%d] avaialble: %d\n",
h,GameValid[h]);
}
else if (DeviceCommand == 22){
memset(codeno, 0, sizeof(codeno));
codeno[0]=buf[4]; // Device ID
codeno[1]=buf[5];
h=atoi(codeno); // Device ID
memset(codeno, 0, sizeof(codeno));
codeno[0]=buf[6]; // Device Valid
codeno[1]=buf[7];
DeviceValid[h]=atoi(codeno); // Scenario Valid
printf("Device[%d] avaialble: %d\n",
h,DeviceValid[h]);
}
else
ScenarioValue=atoi(codeno); // Scenario Value (data)
}
}
if (DataSent==0){
printf("sent: %s\n", sentdata);
DeviceCommand=0; // reset
DeviceData=0; // reset
DataSent=1;
}
}
/*
void* iss( void* args ) // Sensor Node
{
int fin=0, l=0, m=0, n=0,
i,j,k,t;
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 400000000; // 0.4 msec Coomunication Time Interval
k=0;
while(fin<2){
// if (DataSent==0){
// printf("[%d] ID:%d, State:%d Data:%d \n",
// k, DeviceID, DeviceStage, DeviceData);
// k++;
// }
senddata();
nanosleep(&ts, NULL);
}
return NULL;
}
*/
#define TFLITE_MINIMAL_CHECK(x) \
if (!(x)) { \
fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); \
exit(1); \
}
std::vector<double> split(const std::string& str, char delimiter) {
std::vector<double> tokens;
std::string token;
std::istringstream tokenStream(str);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(std::stod(token));
}
return tokens;
}
double compute_new_node_attribute(const std::vector<double>& node_data, const std::vector<double>& centroid_data, const std::string& similarity_type = "cosine") {
double new_node_attribute;
if (similarity_type == "cosine") {
double dot_product = 0.0;
double norm_node_data = 0.0;
double norm_centroid_data = 0.0;
for (size_t i = 0; i < node_data.size(); i++) {
dot_product += node_data[i] * centroid_data[i];
norm_node_data += node_data[i] * node_data[i];
norm_centroid_data += centroid_data[i] * centroid_data[i];
}
norm_node_data = std::sqrt(norm_node_data);
norm_centroid_data = std::sqrt(norm_centroid_data);
new_node_attribute = 1 - (dot_product / (norm_node_data * norm_centroid_data));
} else {
double sum_of_squares = 0.0;
for (size_t i = 0; i < node_data.size(); i++) {
double diff = node_data[i] - centroid_data[i];
sum_of_squares += diff * diff;
}
new_node_attribute = std::sqrt(sum_of_squares);
}
return new_node_attribute;
}
std::vector<double> compute_nodes_attribute(const std::string& cluster_file, std::vector<double>& centroid_data, const std::string& centroid_type = "mean", const std::string& similarity_type = "cosine") {
std::ifstream file(cluster_file);
std::vector<double> nodes_attribute;
std::vector<std::vector<double>> nodes_data;
if (file.is_open()) {
std::string line;
int n_rows = 0;
if (std::getline(file, line)) {
std::vector<double> node_data = split(line, ' ');
for (size_t i = 0; i < node_data.size(); i++) {
centroid_data.push_back(node_data[i]);
}
nodes_data.push_back(node_data);
n_rows += 1;
}
while (std::getline(file, line)) {
std::vector<double> node_data = split(line, ' ');
for (size_t i = 0; i < node_data.size(); i++) {
centroid_data[i] += node_data[i];
}
nodes_data.push_back(node_data);
n_rows += 1;
}
for (size_t i = 0; i < centroid_data.size(); i++) {
centroid_data[i] /= n_rows;
}
}
for (const std::vector<double>& node_data : nodes_data) {
double new_node_attribute = compute_new_node_attribute(node_data, centroid_data, similarity_type);
nodes_attribute.push_back(new_node_attribute);
}
return nodes_attribute;
}
std::vector<std::vector<double>> calculate_centroids(const std::vector<std::string>& file_paths, const std::string& centroid_type = "mean", const std::string& similarity_type = "cosine") {
printf("Similarity type: %s\n", similarity_type.c_str());
std::vector<std::vector<double>> nodes_attributes_per_cluster;
std::vector<std::vector<double>> centroids_per_cluster;
printf("Nodes attributes per cluster initialized\n");
for (const std::string& file_path : file_paths) {
std::vector<double> centroid_vector;
std::vector<double> nodes_attribute = compute_nodes_attribute(file_path, centroid_vector, centroid_type, similarity_type);
nodes_attributes_per_cluster.push_back(nodes_attribute);
centroids_per_cluster.push_back(centroid_vector);
printf("Calculating nodes attributes and centroid for cluster: %s\n", file_path.c_str());
}
return centroids_per_cluster;
}
std::pair<int, std::string> find_similar_class(const std::vector<double>& new_feature_vector, std::vector<std::vector<double>>& centroids_per_cluster, const std::vector<std::string>& class_labels, const std::string& similarity_type = "cosine") {
std::vector<double> new_node_attributes;
int index = 0;
// printf("Calculating current frame similarity values\n");
for (const std::vector<double>& centroid_vector : centroids_per_cluster) {
double new_node_attribute = compute_new_node_attribute(new_feature_vector, centroid_vector, similarity_type);
new_node_attributes.push_back(new_node_attribute);
// printf("Calculating new node's attribute w.r.t. cluster: %s\n", class_labels[index].c_str());
index += 1;
}
// printf("Classifying ...\n");
int class_index = std::distance(new_node_attributes.begin(), std::min_element(new_node_attributes.begin(), new_node_attributes.end()));
// printf("Class index: %d\n", class_index);
printf("Current frame class: %s\n", class_labels[class_index].c_str());
return std::make_pair(class_index, class_labels[class_index]);
}
std::vector<std::string> load_model_labels(std::string labels_file)
{
std::ifstream file(labels_file.c_str());
TFLITE_MINIMAL_CHECK(file.is_open())
printf("Label file loaded from %s\n", labels_file.c_str());
std::string label_str;
std::vector<std::string> labels;
while (std::getline(file, label_str))
{
if (label_str.size() > 0)
labels.push_back(label_str);
}
file.close();
return labels;
}
// Define a callback function for the trackbar
void onTrackbarChange(int sliderValue, void* userdata) {
int* sliderStoredValue = static_cast<int*>(userdata);
*sliderStoredValue = sliderValue;
}
int main(int argc, char **argv)
{
// Get Model, label and input image
const char *modelFileName = "/Users/kubotamacmini/Documents/cognitive_games/mobilenet_v3small-075-224-feature-vector.tflite";
const char *labelFile = "/Users/kubotamacmini/Documents/cognitive_games/efficientnet_labels.txt";
const char *imageFile = "camera";
// Clusters data files
std::vector<std::string> clusters_files_path = {
"/Users/kubotamacmini/Documents/cognitive_games/L_vectors.txt",
"/Users/kubotamacmini/Documents/cognitive_games/L_2_vectors.txt",
"/Users/kubotamacmini/Documents/cognitive_games/L_3_vectors.txt",
// "/Users/kubotamacmini/Documents/cognitive_games/L_4_vectors.txt",
"/Users/kubotamacmini/Documents/cognitive_games/C_vectors.txt",
"/Users/kubotamacmini/Documents/cognitive_games/C_2_vectors.txt",
"/Users/kubotamacmini/Documents/cognitive_games/C_3_vectors.txt",
"/Users/kubotamacmini/Documents/cognitive_games/C_4_vectors.txt",
// "/Users/kubotamacmini/Documents/cognitive_games/C_5_vectors.txt",
"/Users/kubotamacmini/Documents/cognitive_games/None_vectors.txt",
"/Users/kubotamacmini/Documents/cognitive_games/None_letter_vectors.txt",
"/Users/kubotamacmini/Documents/cognitive_games/None_letter_2_vectors.txt",
// "/Users/kubotamacmini/Documents/cognitive_games/None_letter_3_vectors.txt",
"/Users/kubotamacmini/Documents/cognitive_games/None_bg_vectors.txt"
};
std::vector<std::string> class_labels = {
"L",
"L",
"L",
// "L",
"C",
"C",
"C",
"C",
// "C",
"None",
"None",
"None",
"None",
// "None"
};
std::string centroid_type = "mean";// In the meantime only mean is supported
std::string similarity_type = "cosine";//"euclidean";
std::vector<std::vector<double>> centroid_per_cluster = calculate_centroids(clusters_files_path, centroid_type, similarity_type);
printf("Clusters Centroids calculated\n");
// Camera activation and image loading
std::vector<std::string> paths;
bool readFromCamera = false;
paths.push_back("/Users/kubotamacmini/Documents/cognitive_games/apple_above.jpg");
readFromCamera = true;
// Open the default camera
cv::VideoCapture cap(0);
if (readFromCamera && !cap.isOpened()) { // Check if the camera opened successfully
std::cerr << "Error: Unable to open camera" << std::endl;
return -1;
}
printf("Camera opened\n");
// Classificationn model set up
std::unique_ptr<tflite::FlatBufferModel> model = tflite::FlatBufferModel::BuildFromFile(modelFileName);
TFLITE_MINIMAL_CHECK(model != nullptr);
printf("Model loaded \n");
// Initiate Interpreter
tflite::ops::builtin::BuiltinOpResolver resolver;
std::unique_ptr<tflite::Interpreter> interpreter;
tflite::InterpreterBuilder(*model.get(), resolver)(&interpreter); //op: tflite::InterpreterBuilder(*model, resolver)(&interpreter);
TFLITE_MINIMAL_CHECK(interpreter != nullptr);
printf("Interpreter initiated \n");
// Configure the interpreter
// interpreter->SetAllowFp16PrecisionForFp32(true);
interpreter->SetNumThreads(-1);
// Choose a tensor from model by a tensor index
/* Using mobilenet_v3small-075 class
lite0-uint8
Node 61 Operator Builtin Code 9 FULLY_CONNECTED (delegated by node 65)
3 Input Tensors:[161,18,1] -> 0B (0.00MB)
1 Output Tensors:[162] -> 0B (0.00MB)
Node 62 Operator Builtin Code 25 SOFTMAX (not delegated)
1 Input Tensors:[162] -> 1000B (0.00MB)
1 Output Tensors:[163] -> 1000B (0.00MB)
lite1-uint8
Node 81 Operator Builtin Code 9 FULLY_CONNECTED (delegated by node 85)
3 Input Tensors:[211,23,1] -> 0B (0.00MB)
1 Output Tensors:[212] -> 0B (0.00MB)
Node 82 Operator Builtin Code 25 SOFTMAX (not delegated)
1 Input Tensors:[212] -> 1000B (0.00MB)
1 Output Tensors:[213] -> 1000B (0.00MB)
Tensor 212 efficientnet-lite1/mod... kTfLiteInt8 kTfLiteArenaRw 1000 / 0.00 [1,1000] [174080, 175080) <---
Tensor 213 Softmax_int8 kTfLiteInt8 kTfLiteArenaRw 1000 / 0.00 [1,1000] [174080, 175080)
Tensor 214 images kTfLiteUInt8 kTfLiteArenaRw 172800 / 0.16 [1,240,240,3] [0, 172800)
Tensor 215 Softmax kTfLiteUInt8 kTfLiteArenaRw 1000 / 0.00 [1,1000] [172800, 173800)
L_coin
tensor_data_ptr[707]: -128
tensor_data_ptr[708]: -128
tensor_data_ptr[709]: -128
tensor_data_ptr[710]: -128
tensor_data_ptr[711]: -126
tensor_data_ptr[712]: -128
tensor_data_ptr[713]: -126
tensor_data_ptr[714]: -128
tensor_data_ptr[715]: -128
tensor_data_ptr[716]: -128
tensor_data_ptr[717]: -128
tensor_data_ptr[718]: -128
tensor_data_ptr[719]: -128
apple
tensor_data_ptr[707]: -126
tensor_data_ptr[708]: -128
tensor_data_ptr[709]: -128
tensor_data_ptr[710]: -97
tensor_data_ptr[711]: -128
tensor_data_ptr[712]: -128
tensor_data_ptr[713]: -128
tensor_data_ptr[714]: -128
tensor_data_ptr[715]: -128
tensor_data_ptr[716]: -128
tensor_data_ptr[717]: -128
tensor_data_ptr[718]: -128
tensor_data_ptr[719]: -1
lite2-uint8
Node 81 Operator Builtin Code 9 FULLY_CONNECTED (delegated by node 85)
3 Input Tensors:[211,23,1] -> 0B (0.00MB)
1 Output Tensors:[212] -> 0B (0.00MB)
Node 82 Operator Builtin Code 25 SOFTMAX (not delegated)
1 Input Tensors:[212] -> 1000B (0.00MB)
1 Output Tensors:[213] -> 1000B (0.00MB)
Tensor 212 efficientnet-lite2/mod... kTfLiteInt8 kTfLiteArenaRw 1000 / 0.00 [1,1000] [204096, 205096) <---
Tensor 213 Softmax_int8 kTfLiteInt8 kTfLiteArenaRw 1000 / 0.00 [1,1000] [204096, 205096)
Tensor 214 images kTfLiteUInt8 kTfLiteArenaRw 202800 / 0.19 [1,260,260,3] [0, 202800)
Tensor 215 Softmax kTfLiteUInt8 kTfLiteArenaRw 1000 / 0.00 [1,1000] [202816, 203816)
L_coin
tensor_data_ptr[673]: -126
tensor_data_ptr[674]: -128
tensor_data_ptr[675]: -128
tensor_data_ptr[676]: -128
tensor_data_ptr[677]: -127
tensor_data_ptr[678]: -128
tensor_data_ptr[679]: -127
tensor_data_ptr[680]: -128
tensor_data_ptr[681]: -120
tensor_data_ptr[682]: -127
tensor_data_ptr[683]: -128
apple
tensor_data_ptr[673]: -126
tensor_data_ptr[674]: -127
tensor_data_ptr[675]: -128
tensor_data_ptr[676]: -128
tensor_data_ptr[677]: -128
tensor_data_ptr[678]: -128
tensor_data_ptr[679]: -128
tensor_data_ptr[680]: -127
tensor_data_ptr[681]: -128
tensor_data_ptr[682]: -128