Оценка точности преобразования, корректирующего перспективуPython

Программы на Python
Ответить
Anonymous
 Оценка точности преобразования, корректирующего перспективу

Сообщение Anonymous »

Продолжая применение преобразования к изображению на основе QR-кода, я теперь использую маркер ArUco вместо QR-кода. Это изменение существенно не меняет процесс, за исключением того, что здесь я пытаюсь оценить точность преобразования.
Мой подход предполагает обнаружение маркера на изображении и последующее применение преобразования, которое предназначено для того, чтобы не корректировать любые искажения перспективы (поскольку исходное и преобразованное изображения должны быть идентичными). Я делаю это, используя два разных метода. Однако в обоих случаях обнаруженные значения маркера указывают на то, что маркер выглядит искаженным. Я не уверен, как избежать этого искажения.

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

import cv2
import numpy as np
# Load the image containing the ArUco marker
image = cv2.imread('page_1.jpg')
# Get the predefined ArUco dictionary (6x6 markers with 250 entries)
aruco_dict = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_6X6_250)
# Create detector parameters (default values)
parameters = cv2.aruco.DetectorParameters()
detector = cv2.aruco.ArucoDetector(aruco_dict, parameters)
# Detect the markers in the image
markerCorners_ori, markerIds, rejectedCandidates = detector.detectMarkers(image)
cv2.aruco.drawDetectedMarkers(image, markerCorners_ori, markerIds)
# Print the detected marker
print("##########################")
print("#### Marker Detection ####")
print("##########################")
print('Detecting : \n', markerCorners_ori)
print('Marker with and height : \n', markerCorners_ori[0][0][1][0] - markerCorners_ori[0][0][0][0], markerCorners_ori[0][0][2][1] - markerCorners_ori[0][0][1][1])

# Now, I will apply a perspective transformation to the image to correct the marker's perspective
# Here the image is NOT deformed at all and so I expect the final image to be the same as the original image
# I therefore expect the detected marker to be the same as the original marker
EXPECTED_MARKER_SIZE = 188
dest_pts_ori = np.array([[0, 0], [EXPECTED_MARKER_SIZE, 0], [EXPECTED_MARKER_SIZE, EXPECTED_MARKER_SIZE-1], [0, EXPECTED_MARKER_SIZE-1]], dtype='float32')
print("########################")
print("#### DESTINATION PTS####")
print("########################")
print("Destination pts (should be the same as the original marker) : \n",dest_pts_ori)
print('Destination with and height  (should be the same as the original marker): \n', dest_pts_ori[1][0] - dest_pts_ori[0][0], dest_pts_ori[2][1] - dest_pts_ori[1][1])
#
print("########################")
print("#### CASE 1   ##########")
print("########################")
# Case 1  (Using the translation directly)
# Convert the marker corners to a NumPy array
markerCorners = np.array(markerCorners_ori[0], dtype='float32')  # Extract and convert to NumPy array
# This is the translation vector to add to the destination points (Top left corner of the marker in the image)
translation = np.array([293, 1314], dtype='float32')
dest_pts = dest_pts_ori + translation  # Add the translation to the destination points
# Compute the homography matrix
M = cv2.getPerspectiveTransform(markerCorners, dest_pts)
# Perform the perspective transformation
transformed_image_1 = cv2.warpPerspective(image, M, (image.shape[1], image.shape[0]))
# And detect the markers in the transformed image
parameters = cv2.aruco.DetectorParameters()
detector = cv2.aruco.ArucoDetector(aruco_dict, parameters)
markerCorners, markerIds, rejectedCandidates = detector.detectMarkers(transformed_image_1)
print(markerCorners, markerIds)

# Display the image
cv2.imshow('Image with Detected ArUco Markers', transformed_image_1)
cv2.waitKey(0)
cv2.destroyAllWindows()

print("########################")
print("#### CASE 2   ##########")
print("########################")
# Case 2  (Applying the translation to the homography matrix)
# Convert the marker corners to a NumPy array
markerCorners = np.array(markerCorners_ori[0], dtype='float32')  # Extract and convert to NumPy array
# This is the translation vector to add to the destination points (Top left corner of the marker in the image)
# Compute the homography matrix
M = cv2.getPerspectiveTransform(markerCorners, dest_pts_ori)
# ADD the translation to the homography matrix
M[0, 2] += 293  # Add translation on the x-axis
M[1, 2] += 1314  # Add translation on the y-axis
# Perform the perspective transformation
transformed_image_2 = cv2.warpPerspective(image, M, (image.shape[1], image.shape[0]))
# And detect the markers in the transformed image
parameters = cv2.aruco.DetectorParameters()
detector = cv2.aruco.ArucoDetector(aruco_dict, parameters)
markerCorners, markerIds, rejectedCandidates = detector.detectMarkers(transformed_image_2)
print(markerCorners, markerIds)

# Display the image
cv2.imshow('Image with Detected ArUco Markers', transformed_image_2)
cv2.waitKey(0)
cv2.destroyAllWindows()
Это дает

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

##########################
#### Marker Detection ####
##########################
Detecting :
(array([[[ **293.**, 1314.],
[ 481., 1314.],
[ 481., 1501.],
[ **293.**, 1501.]]], dtype=float32),)
Marker with and height :
188.0 187.0
########################
#### DESTINATION PTS####
########################
Destination pts (should be the same as the original marker) :
[[  0.   0.]
[188.   0.]
[188. 187.]
[  0. 187.]]
Destination with and height  (should be the same as the original marker):
188.0 187.0
########################
#### CASE 1   ##########
########################
(array([[[ **290.**, 1311.],
[ 481., 1314.],
[ 481., 1501.],
[ **293.**, 1501.]]], dtype=float32),) [[25]]

########################
#### CASE 2   ##########
########################
(array([[[ **290**., 1311.],
[ 481., 1314.],
[ 481., 1501.],
[ **293**., 1501.]]], dtype=float32),) [[25]]
Изображение



Подробнее здесь: https://stackoverflow.com/questions/791 ... sformation
Ответить

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

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

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

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

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