Views
No views yet
<!-- OpenCV -->
<dependency>
<groupId>org.openpnp</groupId>
<artifactId>opencv</artifactId>
<version>4.9.0-0</version>
</dependency>
<!-- Tess4J -->
<dependency>
<groupId>net.sourceforge.tess4j</groupId>
<artifactId>tess4j</artifactId>
<version>5.13.0</version>
</dependency>static {
OpenCV.loadLocally();
}public static int detectRotation(String imagePath) throws Exception {
ITesseract tesseract = new Tesseract();
tesseract.setDatapath("tessdata");
String osd = tesseract.doOCR(
new java.io.File(imagePath),
java.util.List.of(),
"osd"
);
if (osd.contains("Rotate: 90"))
return 90;
if (osd.contains("Rotate: 180"))
return 180;
if (osd.contains("Rotate: 270"))
return 270;
return 0;
}public static Mat rotate(Mat src, double angle){
Point center = new Point(src.width()/2.0,
src.height()/2.0);
Mat rot = Imgproc.getRotationMatrix2D(center, angle,1);
Mat dst = new Mat();
Imgproc.warpAffine(
src,
dst,
rot,
src.size()
);
return dst;
}public static Mat rotate(Mat src, double angle){
Point center = new Point(src.width()/2.0,
src.height()/2.0);
Mat rot = Imgproc.getRotationMatrix2D(center, angle,1);
Mat dst = new Mat();
Imgproc.warpAffine(
src,
dst,
rot,
src.size()
);
return dst;
}public static double getSkewAngle(Mat image){
Mat gray = new Mat();
Imgproc.cvtColor(image,
gray,
Imgproc.COLOR_BGR2GRAY);
Imgproc.threshold(
gray,
gray,
0,
255,
Imgproc.THRESH_BINARY_INV +
Imgproc.THRESH_OTSU);
MatOfPoint points = new MatOfPoint();
Core.findNonZero(gray, points);
RotatedRect box =
Imgproc.minAreaRect(
new MatOfPoint2f(
points.toArray()));
double angle = box.angle;
if(angle < -45)
angle += 90;
return angle;
}double angle =
Deskew.getSkewAngle(src);
return RotateImage.rotate(src, angle);public static void main(String args[])
throws Exception {
Loader loader = new Loader();
String image = "sample.jpg";
int rotation =
OrientationDetector.detectRotation(image);
Mat img =
Imgcodecs.imread(image);
if(rotation != 0){
img = RotateImage.rotate(
img,
rotation
);
}
img = deskew(img);
Imgcodecs.imwrite(
"output.jpg",
img
);
System.out.println("Completed");
}