答案:使用cv2.line()函数可在图像上绘制直线,参数包括图像、起点、终点、颜色(BGR)和粗细。示例显示在黑色画布或加载图像上画线,需注意坐标系原点在左上角,颜色顺序为BGR,且坐标不能越界。

在Python中使用OpenCV画线,主要依赖于 cv2.line() 函数。这个函数可以让你在图像上绘制一条直线,常用于目标检测、图像标注等场景。
cv2.line(img, pt1, pt2, color, thickness) 的参数说明:
下面是一个完整示例,在一张空白图像上画一条红色直线:
import cv2
import numpy as np
<h1>创建一个黑色图像(300x300 像素,3通道)</h1><p>img = np.zeros((300, 300, 3), dtype=np.uint8)</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p>
<div class="aritcle_card">
<a class="aritcle_card_img" href="/ai/1801">
<img src="https://img.php.cn/upload/ai_manual/000/000/000/175680369151191.png" alt="万兴爱画">
</a>
<div class="aritcle_card_info">
<a href="/ai/1801">万兴爱画</a>
<p>万兴爱画AI绘画生成工具</p>
<div class="">
<img src="/static/images/card_xiazai.png" alt="万兴爱画">
<span>52</span>
</div>
</div>
<a href="/ai/1801" class="aritcle_card_btn">
<span>查看详情</span>
<img src="/static/images/cardxiayige-3.png" alt="万兴爱画">
</a>
</div>
<h1>绘制一条从 (50, 50) 到 (250, 250) 的红色直线,宽度为 3</h1><p>cv2.line(img, (50, 50), (250, 250), (0, 0, 255), 3)</p><h1>显示图像</h1><p>cv2.imshow('Line', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
你也可以在读取的图片上叠加线条:
import cv2
<h1>读取图像</h1><p>img = cv2.imread('example.jpg')</p><h1>在图像上画一条蓝色横线(穿过中间)</h1><p>height, width = img.shape[:2]
cv2.line(img, (0, height//2), (width, height//2), (255, 0, 0), 2)</p><h1>保存或显示</h1><p>cv2.imshow('Image with line', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
基本上就这些。只要掌握 cv2.line() 的用法,就能灵活地在图像中添加直线标注。
以上就是python中使用OpenCV画线的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号