Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<opencv2/core/core.hpp>
- #include<opencv2/highgui/highgui.hpp>
- #include<opencv2/imgproc/imgproc.hpp>
- #include<opencv2/ml/ml.hpp>
- #include <vector>
- #include <time.h>
- #include <unistd.h>
- #include </home/pi/Downloads/libmodbus-3.0.6/src/modbus.h>
- #include <opencv2/opencv.hpp>
- #include<iostream>
- #include<sstream>
- #include "opencv2/core.hpp"
- #include "opencv2/highgui.hpp"
- #include <iostream>
- #include <fstream>
- #include <sstream>
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <errno.h>
- using namespace cv;
- using namespace std;
- using namespace cv::ml;
- Ptr<ml::ANN_MLP> ann;
- //zmienne do komunikacji modbus
- int socket;
- modbus_t *ctx;
- modbus_mapping_t *mb_mapping;
- int rc;
- int use_backend;
- //////////
- vector<Mat> images;
- vector<int> labels;
- Mat train_data, train_labels, test_data, test_labels, test, testl;
- int off = 0;
- int split = 2;
- int nclasses = 10; //ilosc klas - liczby 0-9
- Mat feature;
- bool teach = false; //status nauki, przy rozpoczeciu
- bool modbus_start = false; //status komunikacji
- int pred_prev = 555555; //miejsce przechowywania rozpoznanej litery
- int train_count = 900; //ilosc probek w bazie
- int test_count = 100; //ilosc probek testowych (walidacja)
- float pred_prog = 0.0; //skutecznosc rozpoznania 0.0 - 1.0
- int cap_nr = 0; //wybrana kamera
- vector<int> HASLO = { 2, 7, 3, 5 }; //haslo odblokowujace komunikacje modbus
- int wymiar_hasla = 4; //dlugosc hasla
- //vector<int> HASLO = { 2 };
- vector<int> haslo; //haslo wprowadzane
- void read_image() {
- try {
- for (int j = 0; j < nclasses; j++) {
- int i = 1;
- if (teach == false) { //jesli nie uczy to pobranie tylko zdjec walidacyjnych
- i = train_count - test_count; //900-100 = 800, i pobrane zostana probki 800-900.
- }
- for (; i < train_count; i++) {//pobrane zdjec walidacyjnych
- String aaa = to_string(i);
- String bbb = to_string(j);
- String imagefile = bbb + " (" + aaa + ").png";
- Mat image;
- //wczytuje obrazek a "1" oznacza ze zwraca 3 kanalowy obrazek
- image = imread(imagefile, 1); //wczytanie obrazka
- ///// image=macierz do ktorej jest zapisywanie,rodzaj konwersji
- image.convertTo(image, CV_32F); //konwersja do wymaganego typu
- ////zmiesza obrazek
- resize(image, image, Size(40, 40)); //zmiana wymiaru obrazu na 40x40 pikseli
- /////push_back dodaje do konca vevtora element
- if (!image.data)
- {
- cout << " No image data \n ";
- break;
- }
- feature = image;
- Mat newData = feature.reshape(1, 1);//ustawienie w jednym rzedzie
- if (i >= 800)
- {//pobranie probek walidacyjnych
- test_data.push_back(newData);/////push_back dodaje do konca vevtora element
- test_labels.push_back(j);
- }
- else
- {//pobranie probek trenujacych siec
- train_data.push_back(newData);
- train_labels.push_back(j);
- }
- }
- }
- }
- catch (Exception ex) { //lapanie wyjatku
- // cout << ex.what();
- }
- }
- enum {//modbus
- TCP,
- RTU
- };
- int modbus(int argc, char *argv[]) //prolaczenie komunikacji modbus
- {
- //zmienne przeniesione
- if (argc > 1) {
- if (strcmp(argv[1], "tcp") == 0) {
- use_backend = TCP;
- }
- else if (strcmp(argv[1], "rtu") == 0) {
- use_backend = RTU;
- }
- else {
- printf("Usage:\n %s [tcp|rtu] - Modbus client to measure data bandwith\n\n", argv[0]);
- exit(1);
- }
- }
- else {
- // By default
- use_backend = TCP;
- printf("bandwidth-server-one:\n Running in tcp mode - Modbus client to measure data bandwith\n\n");
- }
- if (use_backend == TCP) {
- printf("Waiting for TCP connection\n");
- ctx = modbus_new_tcp("127.0.0.1", 1502);
- socket = modbus_tcp_listen(ctx, 1);
- modbus_tcp_accept(ctx, &socket);
- printf("TCP connection started!\n");
- }
- else {
- printf("Waiting for Serial connection\n");
- ctx = modbus_new_rtu("/dev/ttyUSB0", 115200, 'N', 8, 1);
- modbus_set_slave(ctx, 1);
- modbus_connect(ctx);
- printf("Serial connection started!\n");
- }
- mb_mapping = modbus_mapping_new(MODBUS_MAX_READ_BITS, 0,
- MODBUS_MAX_READ_REGISTERS, 0);
- if (mb_mapping == NULL) {
- fprintf(stderr, "Failed to allocate the mapping: %s\n",
- modbus_strerror(errno));
- modbus_free(ctx);
- return -1;
- }
- return 1;
- }
- int return_int(int k) { //zamiana wprowadzonych liczb z klawiatury na znaki
- switch (k) {
- case 48: return 0;
- case 49: return 1;
- case 50: return 2;
- case 51: return 3;
- case 52: return 4;
- case 53: return 5;
- case 54: return 6;
- case 55: return 7;
- case 56: return 8;
- case 57: return 9;
- }
- return 10;
- }
- void train_net() {
- int nfeatures = train_data.cols; //oczytanie ilosc w tym przypadku 40x40x3(RGB) = 4800
- if (teach == true) {
- //tworzy pusty model, wyszkie wagi sa ustawioen na zero,nastepnie jest trenowana siec
- //korzystajac z wektorow wejsciowych, naukowa moze byc powtarzana
- ann = ml::ANN_MLP::create();
- //ustawione jest ile jest warst
- Mat_<int> layers(4, 1, CV_32F);
- layers(0) = nfeatures; // input
- layers(1) = nclasses * 8; // hidden
- layers(2) = nclasses * 4; // hidden
- layers(3) = nclasses; // output, 1 pin per class.
- ///ustawienia warst
- ann->setLayerSizes(layers);
- //ustawienei funkcji aktywacj, 0 ,0 to dymysle parametry funkcj aktywacji alfa i beta
- ann->setActivationFunction(ml::ANN_MLP::SIGMOID_SYM, 0, 0);
- ann->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 30, 0.1));
- // druga zmienna setBackpropWeightScale
- ann->setTrainMethod(ml::ANN_MLP::BACKPROP, 0.0001);
- // ann requires "one-hot" encoding of class labels:
- Mat train_classes = Mat::zeros(train_data.rows, nclasses, CV_32FC1);
- for (int i = 0; i < train_classes.rows; i++)
- {
- train_classes.at<float>(i, train_labels.at<int>(i)) = 1.f;
- }
- cout << "Trenuje siec..." << endl;
- ann->train(train_data, ml::ROW_SAMPLE, train_classes);//trening sieci
- }
- else {
- cout << "Pominieto nauke, wczytana nauczona siec z pliku..." << endl;
- ann = cv::Algorithm::load < cv::ml::ANN_MLP >("network93.yaml");
- }
- }
- void walidacja() {
- //validacja
- Mat confusion(nclasses, nclasses, CV_32S, Scalar(0)); //macierz zwracajaca skutecznosc rozpoznania probek walidacyjnych
- for (int i = 0; i < test_data.rows; i++) {
- int pred = 111;//stan poczatkowy
- pred = ann->predict(test_data.row(i), noArray());//rozpoznania bez zwracania wektora accuracy [10,1]
- //cout << "wartosc oczekiwana " << test_labels.row(i) << endl;
- int truth = test_labels.at<int>(i);
- confusion.at<int>(pred, truth)++; //zliczanie skutecznosci
- //cout << "rozpoznane: " + to_string(pred) << endl;
- // waitKey(20);
- }
- cout << " koniec " << endl;
- Mat correct = confusion.diag();
- float accuracy = sum(correct)[0] / sum(confusion)[0];
- cerr << "accuracy: " << accuracy << endl;
- cerr << "confusion:\n" << confusion << endl;
- ann->save("network100.yaml");//zapis wyniku nauki sieci
- }
- int main(int argc, char** argv)
- {
- int a = argc;
- char** a1 = argv;
- //int mdb = modbus(a, a1);
- #ifdef TRAIN
- teach = true;
- #else
- teach = false;
- #endif
- cout << "Wczytuje obrazy..."<< endl;
- read_image();
- cout << "Trenuje siec..."<<endl;
- train_net();
- cout << "Walidacja..."<<endl;
- try {
- walidacja();
- }
- catch (Exception ex) {
- cout << ex.what();
- }
- VideoCapture cap(cap_nr); // open the default camera
- if (!cap.isOpened()) // check if we succeeded
- cout << "Error connect to camera" << endl; // return;
- // Odczytywanie ramki z kamery
- for (;;)
- {
- Mat frame;
- cap >> frame; // get a new frame from camera
- Point A(150, 0); //prostokat 90x160pikseli
- Point B(440, 350);
- Rect RectangleToDraw2(A, B);
- rectangle(frame, RectangleToDraw2.tl(), RectangleToDraw2.br(), Scalar(0, 255, 255), 1, 8, 0);
- //waitKey(1);
- Mat drawing = Mat::zeros(349, 289, CV_8UC3);
- Mat Finish_frame = Mat::zeros(349, 578, CV_8UC3);
- for (int i = 151; i < 440; i++) {//sprawdzamy wiersze i = x
- for (int j = 1; j < 350; j++) {//wszystkie kolumny w wierszu j = y
- Vec3b col = frame.at<Vec3b>(Point(i, j));
- drawing.at<Vec3b>(Point(i - 151, j - 1)) = col;
- }
- }
- for (int i = 151; i < 440; i++) {//sprawdzamy wiersze i = x
- for (int j = 1; j < 350; j++) {//wszystkie kolumny w wierszu j = y
- Vec3b col = frame.at<Vec3b>(Point(i, j));
- Finish_frame.at<Vec3b>(Point(i - 151, j - 1)) = col;
- }
- }
- Mat draw2 = drawing;
- cvtColor(draw2, draw2, CV_BGR2GRAY);
- threshold(draw2, draw2, 125, 255, THRESH_BINARY_INV);
- cvtColor(draw2, draw2, CV_GRAY2RGB);
- for (int i = 1; i < 289; i++) {//sprawdzamy wiersze i = x
- for (int j = 1; j < 349; j++) {//wszystkie kolumny w wierszu j = y
- Vec3b col = draw2.at<Vec3b>(Point(i, j));
- Finish_frame.at<Vec3b>(Point(i + 289, j)) = col;
- }
- }
- imshow("Finish", Finish_frame);
- drawing.convertTo(drawing, CV_32F);
- //imwrite("xd.jpg", drawing);
- try {
- Mat image1;
- image1 = draw2;
- image1.convertTo(image1, CV_32F);
- resize(image1, image1, Size(40, 40));
- ////////////////////////
- Mat test = image1.reshape(1, 1); // flatten to 1 row
- int pred = 111;
- Mat odp;
- pred = ann->predict(test, odp);
- if (pred != pred_prev && odp.at<float>(pred) > 0.5) {
- pred_prev = pred;
- pred_prog = odp.at<float>(pred);
- }
- //modbus pętla
- //for (;;) {
- if (modbus_start == true) {
- uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH];
- rc = modbus_receive(ctx, query);
- if (rc >= 0) {
- printf("Replying to request.\n");
- mb_mapping->tab_input_registers[2669] = pred_prev; // rozpoznana wartosc
- mb_mapping->tab_input_registers[2670] = pred_prog; // próg rozpoznawania
- modbus_reply(ctx, query, rc, mb_mapping);
- }
- else {
- // Connection closed by the client or server
- // break;
- }
- }
- //}
- ///////////////////////////
- int key = waitKey(30);
- string pred_prev_string;
- bool ok = true;
- bool haslo_ok = true;
- int limit;
- String aaa;
- String bbb;
- String imagefile;
- int los = 0;
- int liczba;
- char znak;
- switch (key) {
- case 115: //s zapis nowego obrazka do obrazkow trenujacych
- //imshow("llll", image1);
- srand(time(NULL));
- los = rand() % 750;
- //cout << los << endl;
- cout << "Wcisnij liczbe pod jaka chcesz zapisac w bazie "<< endl;
- liczba = waitKey(0);
- cout << "wcisnieto: " << liczba << endl;
- aaa = to_string(los);
- liczba = return_int(liczba);
- bbb = to_string(liczba);
- imagefile = bbb + " (" + aaa + ").png";
- imwrite(imagefile, image1);
- cout << "zapisano w: " << imagefile << endl;
- break;
- case 110://n nauka sieci
- cout << "Czy na pewno chcesz rozpoczac nauke od nowa? Jeśli tak, wciśnij y" << endl;
- if (waitKey(0) == 121) {
- train_data = NULL; train_labels = NULL; test_data = NULL; test_labels = NULL;
- teach = true;
- cout << "Wczytuje obrazy..."<< endl;
- read_image();
- cout << "Trenuje siec..."<<endl;
- train_net();
- cout << "Walidacja..."<<endl;
- walidacja();
- cout << "Zakonczono..."<<endl;
- }
- cout << "zakończono nauke" << endl;
- break;
- case 120: //x oczyt i zapis obrazka
- pred_prev_string = to_string(pred_prev);
- haslo.push_back(pred_prev);
- limit = haslo.size();
- if (limit > 3) limit = 3;
- for (int i = 0; i < limit; ++i) {
- if (haslo[i] != 0)
- ok = false;
- }
- cout << endl;
- cout << "Accuracy: " << pred_prog << endl;
- cout << "Rozpoznane: " + to_string(pred_prev) << endl;
- if (haslo.size() >= 3 && ok == true) {
- if (haslo.size() == 3) cout << "Podaj haslo." << endl;
- cout << "Haslo: ";
- for (int i = 3; i < haslo.size(); ++i)
- cout << haslo[i];
- cout << endl;
- }
- break;
- case 97: //a podglad hasla
- cout << "Haslo: ";
- for (int i = 3; i < haslo.size(); ++i)
- cout << haslo[i];
- cout << endl;
- break;
- case 99: //c czyszczenie hasla
- haslo.clear();
- cout << "Haslo wyczyszczone." << endl;
- break;
- case 8://backspace
- if (haslo.size() > 0) {
- haslo.pop_back();
- //cout << "Haslo: " << haslo << endl;
- cout << "Haslo: ";
- for (int i = 3; i < haslo.size(); ++i)
- cout << haslo[i];
- cout << endl;
- break;
- case 109://m zakończenie modbusa
- //printf("Quit the loop: %s\n", modbus_strerror(errno));
- if(modbus_start == true){
- cout << "Komunikacja modbus zakonczona." << endl;
- modbus_start = false;
- modbus_mapping_free(mb_mapping);
- close(socket);
- modbus_free(ctx);
- }else{
- cout << "Komunikacja modbus nie zostala otwarta." << endl;
- }
- break;
- case 122://z rozpoczecie modbusa
- if (haslo.size() == (wymiar_hasla+3)) {
- for (int i = 3; i < haslo.size(); ++i) {
- if (haslo[i] != HASLO[i - 3]) {
- haslo_ok = false;
- }
- }
- if (haslo_ok) {
- cout << "Komunikacja Modbus otwarta" << endl;
- if (modbus_start == false) {
- modbus_start = true;
- int mdb = modbus(a, a1);
- if (mdb == 1) {
- }
- }
- //
- }
- else {
- cout << "Haslo bledne " << endl;
- }
- }
- else {
- cout << "Haslo ma zly wymiar" << endl;
- }
- break;
- }
- key = 0;
- }
- }
- catch (Exception ex) {
- //cout << ex.what() << endl;
- }
- }
- waitKey(0);
- return 0;
- }
- //g++ $(pkg-config --libs --cflags opencv libmodbus) -o projekt projekt.cpp
- //g++ $(pkg-config --libs --cflags opencv) -o projekt projekt.cpp
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement