java操作openCV对图片识别签字和写入标记操作
对图片颜色黑色区域比例计算
这里直接上代码了
/**
* 图片颜色黑色区域比例
* @param imageFile 图片路径
* @param startRows 开始高度
* @param endRows 结束高度位置
* @param startCols 开始的列坐标位置
* @param endCols 结束的列坐标位置
*/
public static boolean imageColorBlackRate(String imageFile,int startRows,int endRows,int startCols,int endCols) {
Mat mat = Imgcodecs.imread(imageFile);
if (endCols == 0){
endCols = mat.cols();
}
int num = 0;//记录颜色的像素点
float rate;//要计算的百分率
for (int i = startRows; i < endRows; i++) {
for (int j = startCols; j < endCols; j++) {
double[] doubles = mat.get(i, j);
//对该像素是否为指定颜色进行判断 BGR 像素点
if(doubles[0] <= 120 && doubles[1] <= 120 && doubles[2] <= 120){
num++;
}
}
}
rate = (float)num / (float)((endRows-startRows) * endCols);
//阀值为 0.2以上表示为全黑
if(rate > 0.20){
System.out.println("基本全部为黑色!");
}
return rate;
}
在图片中写入标记
注意: 写入中文时会有编码问题,这个暂时未解决,也一直在寻找解决方法,后期有机会在更新.
/**
* 写入标记
* @param imageFile 图片文件的位置
* @param x 写入位置的横坐标
* @param y 写入位置的纵坐标
* @param scalar 字体的颜色定义 颜色值RGB 0 ~ 255
* @return false or true
*/
public static boolean imageWriteSign(String imageFile,String text,int x,int y,Scalar scalar) {
Mat mat = Imgcodecs.imread(imageFile);
Imgproc.putText(mat,text,new Point(x,y),Imgproc.FONT_HERSHEY_COMPLEX_SMALL,1, scalar,2);//FONT_HERSHEY_COMPLEX_SMALL为文字的样式定义
return Imgcodecs.imwrite(imageFile, mat);
}