Posted on

用OPENCV繪製垂直線

繪製出穿過這兩個點(10,20)和(50,30)的中心點,並與和這兩點相連的直線垂直的線。

import cv2
import numpy as np

# 創建一個空的圖像,並設置其大小為 100x100 像素,並設置其通道數為 3 (RGB)
img = np.zeros((100, 100, 3), np.uint8)

# 定義點的座標
point1 = (10, 20)
point2 = (50, 30)

# 計算兩個點的中心點座標
center_point = ((point1[0] + point2[0]) // 2, (point1[1] + point2[1]) // 2)

# 繪製出兩個點以及中心點
cv2.circle(img, point1, 2, (0, 0, 255), -1)
cv2.circle(img, point2, 2, (0, 0, 255), -1)
cv2.circle(img, center_point, 2, (0, 255, 0), -1)

# 計算與這兩點相連的直線垂直的線的端點座標
if point1[0] == point2[0]:
    # 如果這兩個點的 x 座標相等,則直接在中心點上下各畫一個點,這兩個點就是線的端點
    line_point1 = (center_point[0], 0)
    line_point2 = (center_point[0], 100)
else:
    # 否則,計算這兩個點之間的斜率
    k = (point2[1] - point1[1]) / (point2[0] - point1[0])
    # 計算垂直於這條線的斜率
    vk = -1 / k
    # 計算線的端點座標
    line_point1 = (center_point[0] - 50, int(center_point[1] - vk * 50))
    line_point2 = (center_point[0] + 50, int(center_point[1] + vk * 50))

# 繪製出垂直線
cv2.line(img, line_point1, line_point2, (255, 0, 0), 1)

# 顯示圖像
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()