我正在try 使用OpenCV来检测在白色背景下扫描的卡片的轮廓.然而,我遇到了一个问题,它似乎只是将整个图像检测为1轮廓.在这一点上,我完全被我能调整的东西难住了.我try 过ImgProc.RETRLIST,但它返回42K等高线.
Code:个
public void convert() throws FileNotFoundException {
// Load the image file
// temp
File file = ResourceUtils.getFile("classpath:input_image.png");
// temp change to inputstream
Mat image = Imgcodecs.imread(file.getAbsolutePath());
// Convert the image to grayscale
Mat grayImage = new Mat();
Imgproc.cvtColor(image, grayImage, Imgproc.COLOR_BGR2GRAY);
// Apply a threshold to convert the image to black and white
Mat thresholdImage = new Mat();
Imgproc.threshold(grayImage, thresholdImage, 242, 255, Imgproc.THRESH_BINARY);
Imgcodecs.imwrite("thresh.png", thresholdImage);
// Find contours in the thresholded image
List<MatOfPoint> contours = new ArrayList<>();
Mat hierarchy = new Mat();
Imgproc.findContours(thresholdImage, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
// Set the amount of empty space to add around the cropped image
int emptySpace = 20;
// Loop over the contours
for (int i = 0; i < contours.size(); i++) {
MatOfPoint contour = contours.get(i);
// Find the bounding box of the contour
Rect boundingRect = Imgproc.boundingRect(contour);
// Crop the rectangle from the original image using the bounding box coordinates
Mat rect = new Mat(image, boundingRect);
// Straighten the rectangle
RotatedRect rotatedRect = Imgproc.minAreaRect(new MatOfPoint2f(contour.toArray()));
double angle = rotatedRect.angle;
if (rotatedRect.size.width > rotatedRect.size.height) {
angle += 90;
}
Mat rotationMatrix = Imgproc.getRotationMatrix2D(rotatedRect.center, angle, 1.0);
Mat rotatedRectMat = new Mat();
Imgproc.warpAffine(rect, rotatedRectMat, rotationMatrix, rect.size());
// Add empty space around the cropped image
Mat rectWithBorder = new Mat();
Core.copyMakeBorder(rotatedRectMat, rectWithBorder, emptySpace, emptySpace, emptySpace, emptySpace, Core.BORDER_CONSTANT, new Scalar(255, 255, 255));
// Save the rectangle with border as a separate image file
Imgcodecs.imwrite(String.format("output_image_%d.png", i), rectWithBorder);
}
}
Input Image:
Generated Threshold:个
Output Image:个