在Opencv-Python中用直线将新点连接到图像上的前一个点
OpenCV-Python是一个Python绑定库,旨在解决计算机视觉问题。让我们看看如何用一条直线将一个新点连接到图像上的前一个点。
第 1 步:在图像上绘制点:
在图像上,我们可以使用cv2.circle()方法标记点。此方法用于在任何图像上绘制圆圈。
Syntax: cv2.circle(image, center_coordinates, radius, color, thickness)
Parameters: This method will take the following parameters:
- image: It is the image on which circle is to be drawn.
- center_coordinates: It is the center coordinates of the circle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).
- radius: It is the radius of the circle.
- color: It is the color of the borderline of the circle to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color.
- thickness: It is the thickness of the circle borderline in px. The thickness of -1 px will fill the rectangle shape by the specified color.
Return: It returns an image with a circle drawn on it.
步骤 2:通过直线连接两点:
我们可以使用cv2.line()方法连接图像上的两个点。此方法用于在任何图像上画线。
Syntax: cv2.circle(image, center_coordinates, radius, color, thickness)
Parameters: This method will take the following parameters:
- image: It is the image on which circle is to be drawn.
- center_coordinates: It is the center coordinates of the circle. The coordinates are represented as tuples of two values i.e. (X coordinate value, Y coordinate value).
- radius: It is the radius of the circle.
- color: It is the color of the borderline of the circle to be drawn. For BGR, we pass a tuple. eg: (255, 0, 0) for blue color.
- thickness: It is the thickness of the circle borderline in px. The thickness of -1 px will fill the rectangle shape by the specified color.
Return Value: It returns an image with a line drawn on it.
下面是实现:
Python3
# importing required packages
import cv2
import numpy as np
# mouse call back function
def click_event(event, x, y,
flags, params):
# if the left button of mouse
# is clicked then this
# condition executes
if event == cv2.EVENT_LBUTTONDOWN:
# appending the points we
# clicked to list
points.append((x,y))
# marking the point with a circle
# of center at that point and
# small radius
cv2.circle(img,(x,y), 4,
(0, 255, 0), -1)
# if length of points list
# greater than2 then this
# condition executes
if len(points) >= 2:
# joins the current point and
# the previous point in the
# list with a line
cv2.line(img, points[-1], points[-2],
(0, 255, 255), 5)
# displays the image
cv2.imshow('image', img)
# making an black image
# of size (512,512,3)
# create 3-d numpy
# zeros array
img = np.zeros((512, 512, 3),
np.uint8)
# declare a list to append all the
# points on the image we clicked
points = []
# show the image
cv2.imshow('image',img)
# setting mouse call back
cv2.setMouseCallback('image',
click_event)
# no waiting
cv2.waitKey(0)
# To close the image
# window that we opened
cv2.destroyAllWindows()