Advertisement
Guest User

Untitled

a guest
Jun 13th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.35 KB | None | 0 0
  1. #include<opencv2/core/core.hpp>
  2. #include<opencv2/highgui/highgui.hpp>
  3. #include<opencv2/imgproc/imgproc.hpp>
  4. #include<opencv2/ml/ml.hpp>
  5. #include <vector>
  6. #include <time.h>
  7.  
  8. #include <unistd.h>
  9. #include </home/pi/Downloads/libmodbus-3.0.6/src/modbus.h>
  10.  
  11. #include <opencv2/opencv.hpp>
  12. #include<iostream>
  13. #include<sstream>
  14. #include "opencv2/core.hpp"
  15. #include "opencv2/highgui.hpp"
  16. #include <iostream>
  17. #include <fstream>
  18. #include <sstream>
  19. #include <stdio.h>
  20. #include <string.h>
  21. #include <stdlib.h>
  22. #include <errno.h>
  23.  
  24.  
  25. using namespace cv;
  26. using namespace std;
  27. using namespace cv::ml;
  28.  
  29. Ptr<ml::ANN_MLP> ann;
  30. //zmienne do komunikacji modbus
  31. int socket;
  32. modbus_t *ctx;
  33. modbus_mapping_t *mb_mapping;
  34. int rc;
  35. int use_backend;
  36. //////////
  37. vector<Mat> images;
  38. vector<int> labels;
  39. Mat train_data, train_labels, test_data, test_labels, test, testl;
  40. int off = 0;
  41. int split = 2;
  42. int nclasses = 10; //ilosc klas - liczby 0-9
  43. Mat feature;
  44. bool teach = false; //status nauki, przy rozpoczeciu
  45. bool modbus_start = false; //status komunikacji
  46. int pred_prev = 555555; //miejsce przechowywania rozpoznanej litery
  47. int train_count = 900; //ilosc probek w bazie
  48. int test_count = 100; //ilosc probek testowych (walidacja)
  49. float pred_prog = 0.0; //skutecznosc rozpoznania 0.0 - 1.0
  50. int cap_nr = 0; //wybrana kamera
  51. vector<int> HASLO = { 2, 7, 3, 5 }; //haslo odblokowujace komunikacje modbus
  52. int wymiar_hasla = 4; //dlugosc hasla
  53. //vector<int> HASLO = { 2 };
  54. vector<int> haslo; //haslo wprowadzane
  55.  
  56. void read_image() {
  57. try {
  58. for (int j = 0; j < nclasses; j++) {
  59. int i = 1;
  60. if (teach == false) { //jesli nie uczy to pobranie tylko zdjec walidacyjnych
  61. i = train_count - test_count; //900-100 = 800, i pobrane zostana probki 800-900.
  62. }
  63.  
  64. for (; i < train_count; i++) {//pobrane zdjec walidacyjnych
  65. String aaa = to_string(i);
  66. String bbb = to_string(j);
  67. String imagefile = bbb + " (" + aaa + ").png";
  68. Mat image;
  69. //wczytuje obrazek a "1" oznacza ze zwraca 3 kanalowy obrazek
  70. image = imread(imagefile, 1); //wczytanie obrazka
  71. ///// image=macierz do ktorej jest zapisywanie,rodzaj konwersji
  72. image.convertTo(image, CV_32F); //konwersja do wymaganego typu
  73. ////zmiesza obrazek
  74. resize(image, image, Size(40, 40)); //zmiana wymiaru obrazu na 40x40 pikseli
  75. /////push_back dodaje do konca vevtora element
  76. if (!image.data)
  77. {
  78. cout << " No image data \n ";
  79. break;
  80. }
  81. feature = image;
  82. Mat newData = feature.reshape(1, 1);//ustawienie w jednym rzedzie
  83. if (i >= 800)
  84. {//pobranie probek walidacyjnych
  85. test_data.push_back(newData);/////push_back dodaje do konca vevtora element
  86. test_labels.push_back(j);
  87. }
  88. else
  89. {//pobranie probek trenujacych siec
  90. train_data.push_back(newData);
  91. train_labels.push_back(j);
  92. }
  93. }
  94. }
  95. }
  96. catch (Exception ex) { //lapanie wyjatku
  97. // cout << ex.what();
  98. }
  99. }
  100.  
  101.  
  102. enum {//modbus
  103. TCP,
  104. RTU
  105. };
  106.  
  107. int modbus(int argc, char *argv[]) //prolaczenie komunikacji modbus
  108. {
  109. //zmienne przeniesione
  110. if (argc > 1) {
  111. if (strcmp(argv[1], "tcp") == 0) {
  112. use_backend = TCP;
  113. }
  114. else if (strcmp(argv[1], "rtu") == 0) {
  115. use_backend = RTU;
  116. }
  117. else {
  118. printf("Usage:\n %s [tcp|rtu] - Modbus client to measure data bandwith\n\n", argv[0]);
  119. exit(1);
  120. }
  121. }
  122. else {
  123. // By default
  124. use_backend = TCP;
  125. printf("bandwidth-server-one:\n Running in tcp mode - Modbus client to measure data bandwith\n\n");
  126. }
  127.  
  128. if (use_backend == TCP) {
  129. printf("Waiting for TCP connection\n");
  130. ctx = modbus_new_tcp("127.0.0.1", 1502);
  131. socket = modbus_tcp_listen(ctx, 1);
  132. modbus_tcp_accept(ctx, &socket);
  133. printf("TCP connection started!\n");
  134. }
  135. else {
  136. printf("Waiting for Serial connection\n");
  137. ctx = modbus_new_rtu("/dev/ttyUSB0", 115200, 'N', 8, 1);
  138. modbus_set_slave(ctx, 1);
  139. modbus_connect(ctx);
  140. printf("Serial connection started!\n");
  141. }
  142.  
  143. mb_mapping = modbus_mapping_new(MODBUS_MAX_READ_BITS, 0,
  144. MODBUS_MAX_READ_REGISTERS, 0);
  145. if (mb_mapping == NULL) {
  146. fprintf(stderr, "Failed to allocate the mapping: %s\n",
  147. modbus_strerror(errno));
  148. modbus_free(ctx);
  149. return -1;
  150. }
  151. return 1;
  152. }
  153. int return_int(int k) { //zamiana wprowadzonych liczb z klawiatury na znaki
  154. switch (k) {
  155. case 48: return 0;
  156. case 49: return 1;
  157. case 50: return 2;
  158. case 51: return 3;
  159. case 52: return 4;
  160. case 53: return 5;
  161. case 54: return 6;
  162. case 55: return 7;
  163. case 56: return 8;
  164. case 57: return 9;
  165. }
  166. return 10;
  167. }
  168. void train_net() {
  169. int nfeatures = train_data.cols; //oczytanie ilosc w tym przypadku 40x40x3(RGB) = 4800
  170. if (teach == true) {
  171. //tworzy pusty model, wyszkie wagi sa ustawioen na zero,nastepnie jest trenowana siec
  172. //korzystajac z wektorow wejsciowych, naukowa moze byc powtarzana
  173. ann = ml::ANN_MLP::create();
  174. //ustawione jest ile jest warst
  175. Mat_<int> layers(4, 1, CV_32F);
  176.  
  177. layers(0) = nfeatures; // input
  178. layers(1) = nclasses * 8; // hidden
  179. layers(2) = nclasses * 4; // hidden
  180. layers(3) = nclasses; // output, 1 pin per class.
  181. ///ustawienia warst
  182. ann->setLayerSizes(layers);
  183. //ustawienei funkcji aktywacj, 0 ,0 to dymysle parametry funkcj aktywacji alfa i beta
  184. ann->setActivationFunction(ml::ANN_MLP::SIGMOID_SYM, 0, 0);
  185. ann->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 30, 0.1));
  186. // druga zmienna setBackpropWeightScale
  187. ann->setTrainMethod(ml::ANN_MLP::BACKPROP, 0.0001);
  188.  
  189. // ann requires "one-hot" encoding of class labels:
  190. Mat train_classes = Mat::zeros(train_data.rows, nclasses, CV_32FC1);
  191. for (int i = 0; i < train_classes.rows; i++)
  192. {
  193. train_classes.at<float>(i, train_labels.at<int>(i)) = 1.f;
  194. }
  195. cout << "Trenuje siec..." << endl;
  196. ann->train(train_data, ml::ROW_SAMPLE, train_classes);//trening sieci
  197. }
  198.  
  199. else {
  200. cout << "Pominieto nauke, wczytana nauczona siec z pliku..." << endl;
  201. ann = cv::Algorithm::load < cv::ml::ANN_MLP >("network93.yaml");
  202. }
  203. }
  204. void walidacja() {
  205. //validacja
  206. Mat confusion(nclasses, nclasses, CV_32S, Scalar(0)); //macierz zwracajaca skutecznosc rozpoznania probek walidacyjnych
  207.  
  208. for (int i = 0; i < test_data.rows; i++) {
  209. int pred = 111;//stan poczatkowy
  210. pred = ann->predict(test_data.row(i), noArray());//rozpoznania bez zwracania wektora accuracy [10,1]
  211. //cout << "wartosc oczekiwana " << test_labels.row(i) << endl;
  212. int truth = test_labels.at<int>(i);
  213. confusion.at<int>(pred, truth)++; //zliczanie skutecznosci
  214. //cout << "rozpoznane: " + to_string(pred) << endl;
  215. // waitKey(20);
  216. }
  217. cout << " koniec " << endl;
  218. Mat correct = confusion.diag();
  219. float accuracy = sum(correct)[0] / sum(confusion)[0];
  220. cerr << "accuracy: " << accuracy << endl;
  221. cerr << "confusion:\n" << confusion << endl;
  222. ann->save("network100.yaml");//zapis wyniku nauki sieci
  223. }
  224. int main(int argc, char** argv)
  225. {
  226.  
  227. int a = argc;
  228. char** a1 = argv;
  229. //int mdb = modbus(a, a1);
  230. #ifdef TRAIN
  231. teach = true;
  232. #else
  233. teach = false;
  234. #endif
  235. cout << "Wczytuje obrazy..."<< endl;
  236. read_image();
  237. cout << "Trenuje siec..."<<endl;
  238. train_net();
  239. cout << "Walidacja..."<<endl;
  240.  
  241. try {
  242. walidacja();
  243. }
  244. catch (Exception ex) {
  245. cout << ex.what();
  246. }
  247. VideoCapture cap(cap_nr); // open the default camera
  248. if (!cap.isOpened()) // check if we succeeded
  249. cout << "Error connect to camera" << endl; // return;
  250. // Odczytywanie ramki z kamery
  251. for (;;)
  252. {
  253. Mat frame;
  254. cap >> frame; // get a new frame from camera
  255.  
  256. Point A(150, 0); //prostokat 90x160pikseli
  257. Point B(440, 350);
  258. Rect RectangleToDraw2(A, B);
  259. rectangle(frame, RectangleToDraw2.tl(), RectangleToDraw2.br(), Scalar(0, 255, 255), 1, 8, 0);
  260. //waitKey(1);
  261.  
  262. Mat drawing = Mat::zeros(349, 289, CV_8UC3);
  263. Mat Finish_frame = Mat::zeros(349, 578, CV_8UC3);
  264. for (int i = 151; i < 440; i++) {//sprawdzamy wiersze i = x
  265. for (int j = 1; j < 350; j++) {//wszystkie kolumny w wierszu j = y
  266. Vec3b col = frame.at<Vec3b>(Point(i, j));
  267. drawing.at<Vec3b>(Point(i - 151, j - 1)) = col;
  268. }
  269. }
  270. for (int i = 151; i < 440; i++) {//sprawdzamy wiersze i = x
  271. for (int j = 1; j < 350; j++) {//wszystkie kolumny w wierszu j = y
  272. Vec3b col = frame.at<Vec3b>(Point(i, j));
  273. Finish_frame.at<Vec3b>(Point(i - 151, j - 1)) = col;
  274. }
  275. }
  276. Mat draw2 = drawing;
  277. cvtColor(draw2, draw2, CV_BGR2GRAY);
  278. threshold(draw2, draw2, 125, 255, THRESH_BINARY_INV);
  279. cvtColor(draw2, draw2, CV_GRAY2RGB);
  280. for (int i = 1; i < 289; i++) {//sprawdzamy wiersze i = x
  281. for (int j = 1; j < 349; j++) {//wszystkie kolumny w wierszu j = y
  282. Vec3b col = draw2.at<Vec3b>(Point(i, j));
  283. Finish_frame.at<Vec3b>(Point(i + 289, j)) = col;
  284. }
  285. }
  286. imshow("Finish", Finish_frame);
  287. drawing.convertTo(drawing, CV_32F);
  288. //imwrite("xd.jpg", drawing);
  289.  
  290. try {
  291. Mat image1;
  292. image1 = draw2;
  293. image1.convertTo(image1, CV_32F);
  294. resize(image1, image1, Size(40, 40));
  295.  
  296. ////////////////////////
  297. Mat test = image1.reshape(1, 1); // flatten to 1 row
  298. int pred = 111;
  299. Mat odp;
  300. pred = ann->predict(test, odp);
  301.  
  302. if (pred != pred_prev && odp.at<float>(pred) > 0.5) {
  303. pred_prev = pred;
  304. pred_prog = odp.at<float>(pred);
  305. }
  306. //modbus pętla
  307. //for (;;) {
  308. if (modbus_start == true) {
  309. uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];
  310.  
  311. rc = modbus_receive(ctx, query);
  312. if (rc >= 0) {
  313. printf("Replying to request.\n");
  314. mb_mapping->tab_input_registers[2669] = pred_prev; // rozpoznana wartosc
  315. mb_mapping->tab_input_registers[2670] = pred_prog; // próg rozpoznawania
  316. modbus_reply(ctx, query, rc, mb_mapping);
  317. }
  318. else {
  319. // Connection closed by the client or server
  320. // break;
  321. }
  322. }
  323.  
  324. //}
  325.  
  326.  
  327.  
  328.  
  329. ///////////////////////////
  330.  
  331.  
  332.  
  333.  
  334.  
  335. int key = waitKey(30);
  336. string pred_prev_string;
  337. bool ok = true;
  338. bool haslo_ok = true;
  339. int limit;
  340. String aaa;
  341. String bbb;
  342. String imagefile;
  343. int los = 0;
  344. int liczba;
  345. char znak;
  346. switch (key) {
  347. case 115: //s zapis nowego obrazka do obrazkow trenujacych
  348. //imshow("llll", image1);
  349. srand(time(NULL));
  350. los = rand() % 750;
  351. //cout << los << endl;
  352. cout << "Wcisnij liczbe pod jaka chcesz zapisac w bazie "<< endl;
  353. liczba = waitKey(0);
  354. cout << "wcisnieto: " << liczba << endl;
  355. aaa = to_string(los);
  356. liczba = return_int(liczba);
  357. bbb = to_string(liczba);
  358. imagefile = bbb + " (" + aaa + ").png";
  359. imwrite(imagefile, image1);
  360. cout << "zapisano w: " << imagefile << endl;
  361. break;
  362. case 110://n nauka sieci
  363. cout << "Czy na pewno chcesz rozpoczac nauke od nowa? Jeśli tak, wciśnij y" << endl;
  364. if (waitKey(0) == 121) {
  365. train_data = NULL; train_labels = NULL; test_data = NULL; test_labels = NULL;
  366. teach = true;
  367. cout << "Wczytuje obrazy..."<< endl;
  368. read_image();
  369. cout << "Trenuje siec..."<<endl;
  370. train_net();
  371. cout << "Walidacja..."<<endl;
  372. walidacja();
  373. cout << "Zakonczono..."<<endl;
  374. }
  375. cout << "zakończono nauke" << endl;
  376.  
  377. break;
  378. case 120: //x oczyt i zapis obrazka
  379. pred_prev_string = to_string(pred_prev);
  380. haslo.push_back(pred_prev);
  381. limit = haslo.size();
  382. if (limit > 3) limit = 3;
  383. for (int i = 0; i < limit; ++i) {
  384. if (haslo[i] != 0)
  385. ok = false;
  386. }
  387. cout << endl;
  388. cout << "Accuracy: " << pred_prog << endl;
  389. cout << "Rozpoznane: " + to_string(pred_prev) << endl;
  390.  
  391. if (haslo.size() >= 3 && ok == true) {
  392. if (haslo.size() == 3) cout << "Podaj haslo." << endl;
  393. cout << "Haslo: ";
  394. for (int i = 3; i < haslo.size(); ++i)
  395. cout << haslo[i];
  396. cout << endl;
  397. }
  398. break;
  399. case 97: //a podglad hasla
  400. cout << "Haslo: ";
  401. for (int i = 3; i < haslo.size(); ++i)
  402. cout << haslo[i];
  403. cout << endl;
  404. break;
  405. case 99: //c czyszczenie hasla
  406. haslo.clear();
  407. cout << "Haslo wyczyszczone." << endl;
  408. break;
  409. case 8://backspace
  410. if (haslo.size() > 0) {
  411. haslo.pop_back();
  412. //cout << "Haslo: " << haslo << endl;
  413. cout << "Haslo: ";
  414. for (int i = 3; i < haslo.size(); ++i)
  415. cout << haslo[i];
  416. cout << endl;
  417. break;
  418. case 109://m zakończenie modbusa
  419. //printf("Quit the loop: %s\n", modbus_strerror(errno));
  420. if(modbus_start == true){
  421. cout << "Komunikacja modbus zakonczona." << endl;
  422. modbus_start = false;
  423. modbus_mapping_free(mb_mapping);
  424. close(socket);
  425. modbus_free(ctx);
  426. }else{
  427. cout << "Komunikacja modbus nie zostala otwarta." << endl;
  428. }
  429. break;
  430. case 122://z rozpoczecie modbusa
  431. if (haslo.size() == (wymiar_hasla+3)) {
  432. for (int i = 3; i < haslo.size(); ++i) {
  433. if (haslo[i] != HASLO[i - 3]) {
  434. haslo_ok = false;
  435. }
  436. }
  437. if (haslo_ok) {
  438. cout << "Komunikacja Modbus otwarta" << endl;
  439. if (modbus_start == false) {
  440. modbus_start = true;
  441. int mdb = modbus(a, a1);
  442. if (mdb == 1) {
  443.  
  444. }
  445.  
  446. }
  447. //
  448. }
  449. else {
  450. cout << "Haslo bledne " << endl;
  451. }
  452. }
  453. else {
  454. cout << "Haslo ma zly wymiar" << endl;
  455. }
  456. break;
  457. }
  458. key = 0;
  459. }
  460. }
  461. catch (Exception ex) {
  462. //cout << ex.what() << endl;
  463. }
  464.  
  465. }
  466. waitKey(0);
  467.  
  468. return 0;
  469. }
  470. //g++ $(pkg-config --libs --cflags opencv libmodbus) -o projekt projekt.cpp
  471. //g++ $(pkg-config --libs --cflags opencv) -o projekt projekt.cpp
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement