单色背景图片,在端侧java和opencv分割保存图片。
public static void drawRect(){//分割图片并保存
// 1. 加载由libname参数指定的系统库
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
// 2. 打开图片
Mat src = Imgcodecs.imread(dirPath+"/1.jpg");
if (src.dataAddr()==0){
System.out.println("open file error!");
}
Mat mat = src;
Imgcodecs.imwrite(dirPath+"/1-0.jpg", mat);
//图片转换成灰度
Imgproc.cvtColor(src, src, Imgproc.COLOR_BGR2GRAY,0);
Imgcodecs.imwrite(dirPath+"/1-1.jpg", src);
//高斯模糊
Imgproc.GaussianBlur(src, src, new Size(15, 15), 0);
Imgcodecs.imwrite(dirPath+"/1-2.jpg", src);
//二值化操作
Imgproc.threshold(src,src,0,255,THRESH_BINARY | THRESH_TRIANGLE);
Imgcodecs.imwrite(dirPath+"/1-3.jpg", src);
//轮廓发现--得到contours和hierarchy
List
Mat hierarchy = new Mat();
Imgproc.findContours(src, contours, hierarchy, Imgproc.RETR_TREE, CHAIN_APPROX_SIMPLE, new Point(-1, -1));
Imgcodecs.imwrite(dirPath+"/1-4.jpg", hierarchy);
//相当于创建和原图尺寸相同一张黑色的图,用于后面画线作图
Mat contoursImg = Mat.zeros(mat.size(), CV_8UC3);
for(int i=0;i
// if (rect.width < mat.cols() / 2)
// continue;
//在contoursImg上绘制最大的轮廓
Imgproc.drawContours(contoursImg,contours,i, new Scalar(0,0,255),
2,8,hierarchy,0,new Point(0, 0));
double area = contourArea(contours.get(i));
System.out.println("The "+i+"img area is "+area);
}
Imgcodecs.imwrite(dirPath+"/1-5.jpg", contoursImg);
Mat rectImg = Imgcodecs.imread(dirPath+"/1.jpg");//边缘分割 矩形
for(int i=0;i
// if (rect.width < mat.cols() / 2)
// continue;
Imgproc.rectangle (//画矩形
rectImg, //Matrix obj of the image
new Point(rect.x, rect.y), //p1
new Point(rect.x+rect.width, rect.y+rect.height), //p2
new Scalar(0, 0, 255), //Scalar object for color
2 //Thickness of the line
);
}
Imgcodecs.imwrite(dirPath+"/1-6.jpg", rectImg);
Mat bImg = Imgcodecs.imread(dirPath+"/1.jpg");//边缘分割保存文件
for(int i=0;i
if(recta.x<0){
recta.x = 0;
}
if(recta.y<0){
recta.y = 0;
}
Rect roi = new Rect(recta.x,recta.y,recta.width,recta.height);
//System.out.println("The img area is "+recta.x+","+recta.y+","+recta.width+","+recta.height);
Mat dst = new Mat(bImg,roi);
Imgcodecs.imwrite(dirPath+"/2-"+i+".jpg", dst);
}
}
图片用tflite模型进行分类识别。
pip install tflite-model-maker