Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <QApplication>
- #include "widget.h"
- using namespace std;
- using namespace cv;
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- Mat fg = imread("C:\\Users\\Roman\\Pictures\\pf8.bmp");
- Mat bg = imread("C:\\Users\\Roman\\Pictures\\background.bmp");
- if(fg.empty()) {
- cout << "I can`t read fg file";
- return -1;
- }
- if(bg.empty()) {
- cout << "I can`t read bg file";
- return -1;
- }
- if(fg.size != bg.size) {
- cout << "Input image have different size!";
- return -2;
- }
- if(fg.rows > 500 && fg.cols > 500) resize(fg, fg, Size(), 0.5, 0.5, INTER_LINEAR);
- if(fg.rows > 500 && fg.cols > 500) resize(fg, fg, Size(), 0.5, 0.5, INTER_LINEAR);
- if(bg.rows > 500 && bg.cols > 500) resize(bg, bg, Size(), 0.5, 0.5, INTER_LINEAR);
- if(bg.rows > 500 && bg.cols > 500) resize(bg, bg, Size(), 0.5, 0.5, INTER_LINEAR);
- Mat distance = Mat::zeros(fg.rows, fg.cols, CV_32F);
- vector<Mat> fgChannels;
- split(fg, fgChannels);
- vector<Mat> bgChannels;
- split(bg, bgChannels);
- for(size_t i = 0; i < fgChannels.size(); i++) {
- Mat temp = abs(fgChannels[i] - bgChannels[i]);
- temp.convertTo(temp, CV_32F);
- distance = distance + temp;
- }
- Mat mask;
- threshold(distance, mask, 100, 255, THRESH_TOZERO); // Убираем фон
- mask.convertTo(mask, CV_8UC1); // Преобразование в 8 битное 1 канальное изображение
- vector<vector<Point>> contours;
- findContours(mask, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE); // Находим контуры
- drawContours(mask, contours, -1, Scalar(255), FILLED); // Заполняем найденные замкнутые контуры
- Mat crop(fg.rows, fg.cols, CV_8UC3);
- crop.setTo(Scalar(0, 255, 0));
- fg.copyTo(crop, mask);
- normalize(mask.clone(), mask, 0.0, 255.0, NORM_MINMAX, CV_8UC1);
- imwrite("cropped_preform.png", crop);
- imshow("cropped_preform", crop);
- //Canny(crop, mask, 100, 200);
- if(crop.empty()) {
- cout << "Don`t find crop image";
- return 3;
- }
- vector<vector<Point>> contours_poly(contours.size());
- vector<Rect> boundRect(contours.size());
- for(size_t i = 0; i < contours.size(); i++) {
- approxPolyDP(contours[i], contours_poly[i], 3, true);
- boundRect[i] = boundingRect(contours_poly[i]);
- }
- Mat drawing = Mat::zeros(mask.rows, mask.cols, CV_8UC3);
- for(size_t i = 0; i < contours.size(); i++) {
- drawContours(drawing, contours_poly, (int)i, Scalar(0, 255, 0));
- rectangle(drawing, boundRect[i].tl(), boundRect[i].br(), Scalar(0, 255, 0), 1);
- }
- imshow("Bound", drawing);
- waitKey(0);
- destroyAllWindows();
- return a.exec();
- }
Advertisement
Add Comment
Please, Sign In to add comment