Drawing lines in OpenCV is primarily accomplished using the cv2.line() function. This function requires several parameters, including the image, start coordinates, end coordinates, color, and line thickness. Here is a specific example demonstrating how to draw a line on an image:
pythonimport cv2 import numpy as np # Create a black image img = np.zeros((512, 512, 3), np.uint8) # Define the start and end points of the line start_point = (0, 0) # Start coordinates end_point = (511, 511) # End coordinates # Define the line color (white) color = (255, 255, 255) # Define the line thickness thickness = 5 # Draw the line using cv2.line() cv2.line(img, start_point, end_point, color, thickness) # Display the image cv2.imshow('Image with line', img) cv2.waitKey(0) cv2.destroyAllWindows()
In this example, we first create a 512x512 pixel black image. Then, we define the start and end points of the line, specifically drawing from the top-left corner (0, 0) to the bottom-right corner (511, 511). Next, we set the line color to white and the thickness to 5 pixels.
By calling the cv2.line() function, we draw a white diagonal line on the image. Using cv2.imshow() displays this image, cv2.waitKey(0) keeps the window open until keyboard input is received, and finally cv2.destroyAllWindows() closes all open windows.
This function is highly flexible and can be adjusted to modify the line color, thickness, or position to meet various drawing requirements.