How can I draw a line with rectangular corners with OpenCV line, I don't want to use OpenCV's rectangle for some reason. I have posted my code below and output as well, In the output line is curved at the endpoint and start points, I require it as a rectangle.
I searched a lot for that, but it seems no one had that problem before.
import cv2
thickness = 24
img1 = cv2.imread("AMIR4.jpg")
cv2.line(img1, (190,55), (85,55), (255,0,0), (thickness))
cv2.imshow("image", img1)
cv2.waitKey(0)
Sample:
According to OpenCV docs , line() function will draw thick lines with rounding endings .
That being said, you cannot directly get over this issue. You could draw a line several times with thickness=1
:
cv2.line(img1, (190, 55), (85, 55), (255, 0, 0), 1)
cv2.line(img1, (190, 56), (85, 56), (255, 0, 0), 1)
cv2.line(img1, (190, 57), (85, 57), (255, 0, 0), 1)
...
And although you're reluctant, I would suggest simply drawing a filled rectangle instead.
I can see how the cv2.rectangle()
method wouldn't work for you if you want the lines to be able to have any rotation .
So here is a function I defined that works just like the cv2.line()
method, but will result in rectangular ends rather than circular ends:
def draw_line(img, pt1, pt2, color, thickness):
x1, y1, x2, y2 = *pt1, *pt2
theta = np.pi - np.arctan2(y1 - y2, x1 - x2)
dx = int(np.sin(theta) * thickness / 2)
dy = int(np.cos(theta) * thickness / 2)
pts = [
[x1 + dx, y1 + dy],
[x1 - dx, y1 - dy],
[x2 - dx, y2 - dy],
[x2 + dx, y2 + dy]
]
cv2.fillPoly(img, [np.array(pts)], color)
Testing alongside the cv2.line()
method:
import cv2
import numpy as np
def draw_line(img, pt1, pt2, color, thickness):
x1, y1, x2, y2 = *pt1, *pt2
theta = np.pi - np.arctan2(y1 - y2, x1 - x2)
dx = int(np.sin(theta) * thickness / 2)
dy = int(np.cos(theta) * thickness / 2)
pts = [
[x1 + dx, y1 + dy],
[x1 - dx, y1 - dy],
[x2 - dx, y2 - dy],
[x2 + dx, y2 + dy]
]
cv2.fillPoly(img, [np.array(pts)], color)
img = np.full((600, 600, 3), 255, np.uint8)
pt1 = np.random.randint(0, 600, 2)
pt2 = np.random.randint(0, 600, 2)
draw_line(img, pt1, pt2, (0, 0, 0), 15)
cv2.line(img, pt1, pt2, (255, 255, 255), 1)
cv2.imshow("Image", img)
cv2.waitKey(0)
Output (will vary because of the np.random.randint()
):
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.