Map many coordinates to cv2.line efficiently

Viewed 32

What's the most efficient (fastest) way to map a pd.DataFrame of coordinates (x1, x2, y1, y2) to the cv2.line() function?

import cv2
import pandas as pd
    
test = pd.DataFrame({'x1': [1, 2], 'x2': [3, 4], 'y1': [1, 2], 'y2': [3, 4]})

From here, there would be some form of function to map to cv2.line, like this:

map(test, cv2.line((x1, y1), (x2, y2), (0, 0, 255), 1)
1 Answers

Here is one way to do it:

import cv2
import numpy as np
import pandas as pd

test = pd.DataFrame({"x1": [1, 2], "x2": [3, 4], "y1": [1, 2], "y2": [3, 4]})

# cv2.line takes an image as first argument
image = np.ones((800, 600)) * 255

test["image"] = test.apply(
    lambda df_: cv2.line(
        image, (df_["x1"], df_["y1"]), (df_["x2"], df_["y2"]), (0, 0, 255), 1
    ),
    axis=1,
)

for i, img in enumerate(test["image"]):
    cv2.imshow("image_{i}", img)
    cv2.waitKey()
Related