-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrop.cpp
More file actions
119 lines (102 loc) · 2.1 KB
/
Copy pathcrop.cpp
File metadata and controls
119 lines (102 loc) · 2.1 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
// Prototype.cpp : Defines the entry point for the console application.
#include <iostream>
#include <fstream>
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/stitching.hpp"
#include <sstream>
#include <string.h>
using namespace cv;
using namespace std;
bool check_row(Mat image, int y, Rect roi) //returns true if black pixels found
{
int black_count = 0;
for (int x = roi.x; x < roi.width; x++)
{
Scalar intensity = image.at<uchar>(y, x);
if (intensity.val[0] == 0)
{
black_count++;
}
if (black_count>0)
{
return true;
}
}
return false;
}
bool check_col(Mat image, int x, Rect roi) //returns true if black pixels found
{
int black_count = 0;
for (int y = roi.y; y < roi.height; y++)
{
Scalar intensity = image.at<uchar>(y, x);
if (intensity.val[0] == 0)
{
black_count++;
}
if (black_count>0)
{
return true;
}
}
return false;
}
void cropper(Mat &src, Mat &dest)
{
//Crops all blank/black pixels from image borders
//Minimum area cropped per call = 2x+2y pixels
//Preserving backup of original input image
Mat original = src;
//Convert input image to gray
cvtColor(src, src, CV_BGR2GRAY);
//Initialize ROI
Rect roi(0, 0, src.cols, src.rows);
while (1)
{
//Check edges for black/blank pixels
bool left_edge = check_col(src, roi.x, roi);
bool bottom_edge = check_row(src, roi.y + roi.height - 1, roi);
bool right_edge = check_col(src, roi.x + roi.width - 1, roi);
bool top_edge = check_row(src, roi.y, roi);
if (!(left_edge || bottom_edge || right_edge || top_edge))
{
//Shrinking each edge of ROI by 1 pixel width
//To compensate for black/blank pixels lying on ROI boundary
roi.x++;
roi.y++;
roi.height--;
roi.width--;
//Extracting ROI
dest = original(roi);
break;
}
if (left_edge)
{
roi.x++;
roi.width--;
}
if (bottom_edge)
{
roi.height--;
}
if (right_edge)
{
roi.width--;
}
if (top_edge)
{
roi.y++;
roi.height--;
}
}
}
int main()
{
Mat image1;
image1 = imread("final.jpg");
cropper(image1,image1);
imwrite("a.jpg",image1);
waitKey(0);
return 0;
}