OpenCV, проблема коррекции перспективы, нелинейныйJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 OpenCV, проблема коррекции перспективы, нелинейный

Сообщение Anonymous »

У меня есть следующий код для коррекции перспективы, но в результате получается изображение, растянутое по маленьким координатам X и сжатое по большим, как это видно на следующих изображениях.
Исходное изображение, обозначающее конверсию ->
Изображение

Выходное изображение ->
Изображение

код такой

Код: Выделить всё

public class Transformer {

static {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}

/**
* Transforms an image using four points, adjusting the size of the output image
* to be as large as possible based on the points and the aspect ratio.
*
* @param fileIn      Path to the input image.
* @param points      Four points in the original image defined in the following
*                    order: - (x1, y1): top-left - (x2, y2): top-right - (x3,
*                    y3): bottom-right - (x4, y4): bottom-left
* @param fileOut     Path where the transformed image will be saved.
* @param aspectRatio Width/height ratio of the output image.   top-right
double width2 = dinstance(points[3], points[2]); // bottom-left -> bottom-right
double widthDest = (width1 + width2) / 2.0;

double height1 = dinstance(points[0], points[3]); // top-left -> bottom-left
double height2 = dinstance(points[1], points[2]); // top-right -> bottom-right
double heightDest = (height1 + height2) / 2.0;

if (aspectRatio > 0) {

// Adjust dimensions according to aspect ratio
if (widthDest / heightDest > aspectRatio) {
heightDest = widthDest / aspectRatio;
} else {
widthDest = heightDest * aspectRatio;
}
}

// Final dimensions of the output image
int finalWidth = (int) Math.round(widthDest);
int finalHeight = (int) Math.round(heightDest);

log("Original size: " + imageOrig.width() + "x" + imageOrig.height());
log("Final size   : " + finalWidth + "x" + finalHeight);

// Define the destination points
MatOfPoint2f pointsDest = new MatOfPoint2f(new Point(0, 0), // top-left
new Point(finalWidth - 1, 0), // top-right
new Point(finalWidth - 1, finalHeight - 1), // bottom-right
new Point(0, finalHeight - 1) // bottom-left
);

// Define the original points
MatOfPoint2f pointsOrig = new MatOfPoint2f(points);

// Calculate the perspective transformation matrix
Mat transformationMat = Imgproc.getPerspectiveTransform(pointsOrig, pointsDest);

// Create the transformed image with white background
Mat imageTransformed = new Mat(finalHeight, finalWidth, imageOrig.type(), new Scalar(255, 255, 255));

// Apply transformation
Imgproc.warpPerspective(imageOrig, imageTransformed, transformationMat, new Size(finalWidth, finalHeight),
Imgproc.INTER_LINEAR, Core.BORDER_CONSTANT, new Scalar(255, 255, 255));

// Save final image
boolean guardado = Imgcodecs.imwrite(fileOut, imageTransformed);
if (guardado) {
log("Image saved to " + fileOut);
} else {
log("Error saving image " + fileOut);
}
}

private static void log(String msg) {
System.out.println(msg);
}

/**
* Calculates the Euclidean distance between two points.
*
* @param p1 First point.
* @param p2 Second point.
* @return Distance between p1 and p2.
*/
private static double dinstance(Point p1, Point p2) {
return Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}

public static void main(String[] args) {

String fileIn = "input.jpg";
String fileOut = "out.jpg";

Point[] points = {
new Point(76, 0),   // top-left
new Point(141, 14),   // top-right
new Point(127, 174),  // bottom-right
new Point(0, 174)    // bottom-left
};

double aspectRatio = 0; // automatico

transform(ficheroEntrada, puntos, ficheroSalida, aspectRatio);
}

}
код берет область изображения, плоскость которой не является фронтальной, и генерирует новое изображение, эквивалентное фронтальному виду.

Подробнее здесь: https://stackoverflow.com/questions/793 ... -nonlinear
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • OpenCV, проблема коррекции перспективы, нелинейный
    Anonymous » » в форуме JAVA
    0 Ответы
    17 Просмотры
    Последнее сообщение Anonymous
  • OpenCV, проблема коррекции перспективы, нелинейный
    Anonymous » » в форуме JAVA
    0 Ответы
    7 Просмотры
    Последнее сообщение Anonymous
  • OpenCV, проблема коррекции перспективы, нелинейный
    Anonymous » » в форуме JAVA
    0 Ответы
    6 Просмотры
    Последнее сообщение Anonymous
  • Преобразование перспективы с высоты птичьего полета из калибровки камеры opencv python
    Гость » » в форуме Python
    0 Ответы
    53 Просмотры
    Последнее сообщение Гость
  • Преобразование перспективы изображения с использованием Android OpenCV
    Anonymous » » в форуме Android
    0 Ответы
    22 Просмотры
    Последнее сообщение Anonymous

Вернуться в «JAVA»