#!/usr/bin/python3

################################################################################
# Perspective correction
# 
# Note: the source and targe points for determining the project are tweaked
#       for the Unleash demo.
#
# Version: 14 Nov 2021
# Author : <NAME> - <EMAIL>
#
# License: MIT
# Copyright (c) 2021 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
################################################################################ 

import numpy as np
import cv2

# Create the projection matrix based on the landmark correspondance between 2 images
# Note: if no targets/sources points are given, we have defaults values for the Demo
def ipm(source_points = None, target_points = None):

    if source_points is None:

        source_points = np.array(
            [[551, 1031],
            [487, 826],
            [480, 366],
            [964, 280]], dtype=np.float32
        )

    if target_points is None:

        target_points = np.array(
            [[404, 196],
            [522, 202],
            [1252, 339],
            [1101, 752]], dtype=np.float32
        )

    # Compute projection matrix
    M = cv2.getPerspectiveTransform(source_points, target_points)    
    return M

# Using the matrix generated by the `ipm` function, convert the coordinate of a pixel
# in a source image to the destination images
def convert_coordinates(point, M):
    orig_px = point[point[0], point[1], 1  ]
    tf_orig_px = M.dot(orig_px)
    tf_orig_px = M.dot(orig_px) / tf_orig_px[2]
    return tf_orig_px

# Using the matrix generated by the `ipm` function, convert the coordinate of a set of pixels
# in a source image to the destination images
def convert_set_cooordinates(points, M):
    orig_pxs = np.array([[x, y, 1] for [x, y] in points]).T    
    tf_orig_pxs = M.dot(orig_pxs)
    tf_orig_pxs /= tf_orig_pxs[2]
    transf_points = np.array([[x,y] for [x, y] in tf_orig_pxs[:2].T])
    return transf_points


def test():

    import matplotlib
    matplotlib.use("GTK3Agg")
    import matplotlib.pyplot as plt

    # Reading an input file
    im_cam_view = "input/camera_view.png"

    im = plt.imread(im_cam_view)

    # Compute the transformation matrix
    M = ipm()

    # Warp the image
    warped = cv2.warpPerspective(im, M, (im.shape[:2][1], im.shape[:2][0]), flags=cv2.INTER_LANCZOS4, borderMode=cv2.BORDER_CONSTANT, borderValue=0)

    # Convert a point to new coordinates
    orig_px = [1026, 408, 1]
    tf_orig_px = M.dot(orig_px)
    tf_orig_px = M.dot(orig_px) / tf_orig_px[2]    

    # Draw results
    fig, ax = plt.subplots(1, 2)
    ax[0].imshow(im)
    ax[0].set_title('Front View')
    ax[0].plot(orig_px[0], orig_px[1], 'bo')
    ax[1].imshow(warped)
    ax[1].set_title('IPM')
    ax[1].plot(tf_orig_px[0], tf_orig_px[1], 'bo')
    plt.tight_layout()
    plt.show()

# Testing code
if __name__ == '__main__':
    test()
    

#!/usr/bin/python3

################################################################################
# Perspective correction
# 
# Note: the source and targe points for determining the project are tweaked
#       for the Unleash demo.
#
# Version: 14 Nov 2021
# Author : <NAME> - <EMAIL>
#
# License: MIT
# Copyright (c) 2021 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
################################################################################ 

import numpy as np
import cv2

# Create the projection matrix based on the landmark correspondance between 2 images
# Note: if no targets/sources points are given, we have defaults values for the Demo
def ipm(source_points = None, target_points = None):

    if source_points is None:

        source_points = np.array(
            [[551, 1031],
            [487, 826],
            [480, 366],
            [964, 280]], dtype=np.float32
        )

    if target_points is None:

        target_points = np.array(
            [[404, 196],
            [522, 202],
            [1252, 339],
            [1101, 752]], dtype=np.float32
        )

    # Compute projection matrix
    M = cv2.getPerspectiveTransform(source_points, target_points)    
    return M

# Using the matrix generated by the `ipm` function, convert the coordinate of a pixel
# in a source image to the destination images
def convert_coordinates(point, M):
    orig_px = point[point[0], point[1], 1  ]
    tf_orig_px = M.dot(orig_px)
    tf_orig_px = M.dot(orig_px) / tf_orig_px[2]
    return tf_orig_px

# Using the matrix generated by the `ipm` function, convert the coordinate of a set of pixels
# in a source image to the destination images
def convert_set_cooordinates(points, M):
    orig_pxs = np.array([[x, y, 1] for [x, y] in points]).T    
    tf_orig_pxs = M.dot(orig_pxs)
    tf_orig_pxs /= tf_orig_pxs[2]
    transf_points = np.array([[x,y] for [x, y] in tf_orig_pxs[:2].T])
    return transf_points


def test():

    import matplotlib
    matplotlib.use("GTK3Agg")
    import matplotlib.pyplot as plt

    # Reading an input file
    im_cam_view = "input/camera_view.png"

    im = plt.imread(im_cam_view)

    # Compute the transformation matrix
    M = ipm()

    # Warp the image
    warped = cv2.warpPerspective(im, M, (im.shape[:2][1], im.shape[:2][0]), flags=cv2.INTER_LANCZOS4, borderMode=cv2.BORDER_CONSTANT, borderValue=0)

    # Convert a point to new coordinates
    orig_px = [1026, 408, 1]
    tf_orig_px = M.dot(orig_px)
    tf_orig_px = M.dot(orig_px) / tf_orig_px[2]    

    # Draw results
    fig, ax = plt.subplots(1, 2)
    ax[0].imshow(im)
    ax[0].set_title('Front View')
    ax[0].plot(orig_px[0], orig_px[1], 'bo')
    ax[1].imshow(warped)
    ax[1].set_title('IPM')
    ax[1].plot(tf_orig_px[0], tf_orig_px[1], 'bo')
    plt.tight_layout()
    plt.show()

# Testing code
if __name__ == '__main__':
    test()
    

#!/usr/bin/python3 ################################################################################ # Perspective correction # # Note: the source and targe points for determining the project are tweaked #       for the Unleash demo. # # Version: 14 Nov 2021 # Author : <NAME> - <EMAIL> # # License: MIT # Copyright (c) 2021 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ################################################################################ # Create the projection matrix based on the landmark correspondance between 2 images # Note: if no targets/sources points are given, we have defaults values for the Demo # Compute projection matrix # Using the matrix generated by the `ipm` function, convert the coordinate of a pixel # in a source image to the destination images # Using the matrix generated by the `ipm` function, convert the coordinate of a set of pixels # in a source image to the destination images # Reading an input file # Compute the transformation matrix # Warp the image # Convert a point to new coordinates # Draw results # Testing code