Numpy 如何使用给定的坐标在图像中绘制点

Numpy 如何使用给定的坐标在图像中绘制点

在本文中,我们将介绍如何使用Numpy在图像中绘制一个点。

阅读更多:Numpy 教程

准备工作

我们需要安装Numpy库,以便能够使用Numpy中的函数。可以使用以下命令安装:

pip install numpy

我们还需要导入库,并创建一个空白图像。这里我们使用Python的OpenCV库来创建空白图像,并且显示该图像:

import cv2
import numpy as np

# Create a black image
img = np.zeros((512, 512, 3), np.uint8)

# Show the black image
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

这会创建一个512×512像素的黑色图像,并显示出来。

绘制一个点

使用以下代码可以在图像中的指定坐标上绘制一个点:

# Draw a point at (250, 250) with red color
img[250, 250] = [0, 0, 255]

这会在图像的(250,250)处绘制一个红色的点。图像的每个像素由三个值组成,表示它的蓝色,绿色和红色分量。在这里,我们将(250,250)处的蓝色和绿色分量设置为0,红色分量设置为255,因此它是红色的。

绘制多个点

要在图像中绘制多个点,我们可以使用一个循环。在下面的代码中,我们在图像中随机绘制20个点:

# Draw 20 random points
for i in range(20):
    x = np.random.randint(0, 512)
    y = np.random.randint(0, 512)
    img[x, y] = [255, 0, 0]

# Show the modified image
cv2.imshow('Image with points', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

这会在图像中随机绘制20个蓝点

使用OpenCV的函数在图像中绘制点

OpenCV提供了一些用于绘制不同形状的函数,如线,圆等。其中绘制一个圆的函数是cv2.circle()。我们可以使用cv2.circle()函数在图像中绘制一个圆,在这个圆上我们可以选择随意地添加点。

import cv2
import numpy as np

# create a black image
img = np.zeros((512,512,3), np.uint8)

# draw a circle on the image
center_coordinates = (256, 256)
radius = 50
color = (0, 0, 255) 
thickness = 3
cv2.circle(img, center_coordinates, radius, color, thickness) 

# add dots on the image for decoration
img[242, 253] = [255, 0, 0]
img[266, 243] = [255, 0, 0]
img[242, 269] = [255, 0, 0]
img[266, 277] = [255, 0, 0]

# show the image
cv2.imshow('Image with circle and points', img)

cv2.waitKey(0)
cv2.destroyAllWindows()

上述代码会在中心坐标为(256, 256),半径为50的位置画一个红色圆,周围点使用蓝色绘制。

总结

在本文中,我们介绍了如何使用Numpy和OpenCV在图像中绘制点。我们学习了如何以编程方式创建图像,并使用基本的颜色操作在指定像素位置绘制点。我们还了解了如何使用循环绘制多个点,并了解了如何使用OpenCV函数在图像中绘制圆,并在圆上添加点。这些技巧可以在计算机视觉和图像处理中非常有用。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程