1 | initial version |
try this code.
i get these images ( to get second image uncomment commented lines )
Mat src = Imgcodecs.imread("d:/bt.png");
Mat bt = new Mat();
Imgproc.cvtColor(src, bt, Imgproc.COLOR_BGR2GRAY);
Imgproc.threshold(bt, bt, 0, 255, Imgproc.THRESH_BINARY);
Imgcodecs.imwrite("d:/bw.png",bt);
int xmin = bt.cols();
int ymin = bt.rows();
int xmax=0;
int ymax=0;
double[] pixel = new double[0];
for (int x = 0; x < bt.cols(); x++) {
for (int y = 0; y < bt.rows(); y++) {
pixel = bt.get(y, x);
if( pixel[0] == 0)
{
if( x < xmin )
{
xmin = x;
}
if( y < ymin )
{
ymin = y;
}
if( x > xmax )
{
xmax = x;
}
if( y > ymax )
{
ymax = y;
}
}
}
}
//xmin = xmin - 3; // you can try to uncomment these lines
//ymin = ymin - 3;
//xmax = xmax + 3;
//ymax = ymax + 3;
Rect roi = new Rect(xmin, ymin, xmax-xmin, ymax-ymin);
Mat cr = new Mat(src, roi);
2 | No.2 Revision |
try this code.
i get these images ( to get second image uncomment commented lines )
Note: with C++ the easiest way is to use findNonZero()
and boundingRect()
functions to achieve this like explained here
Mat src = Imgcodecs.imread("d:/bt.png");
Mat bt = new Mat();
Imgproc.cvtColor(src, bt, Imgproc.COLOR_BGR2GRAY);
Imgproc.threshold(bt, bt, 0, 255, Imgproc.THRESH_BINARY);
Imgcodecs.imwrite("d:/bw.png",bt);
int xmin = bt.cols();
int ymin = bt.rows();
int xmax=0;
int ymax=0;
double[] pixel = new double[0];
for (int x = 0; x < bt.cols(); x++) {
for (int y = 0; y < bt.rows(); y++) {
pixel = bt.get(y, x);
if( pixel[0] == 0)
{
if( x < xmin )
{
xmin = x;
}
if( y < ymin )
{
ymin = y;
}
if( x > xmax )
{
xmax = x;
}
if( y > ymax )
{
ymax = y;
}
}
}
}
//xmin = xmin - 3; // you can try to uncomment these lines
//ymin = ymin - 3;
//xmax = xmax + 3;
//ymax = ymax + 3;
Rect roi = new Rect(xmin, ymin, xmax-xmin, ymax-ymin);
Mat cr = new Mat(src, roi);