opencv-python学习笔记(一):画线、打开摄像头

前提:

uv

安装依赖:

pyproject.toml:

bash 复制代码
[project]
name = "opencv_learn"
version = "0.1.0"
description = "opencv learn"
readme = "README.md"
requires-python = ">=3.13, < 3.14"
dependencies = [
    "opencv-python>=4.12.0.88",
]
bash 复制代码
uv sync

画线代码:

01_opencv_draw_line.py:

python 复制代码
import cv2
import numpy as np


img = np.zeros((512, 512, 3), np.uint8)


for i in range(512):
    img[:, i] = (0, 0, 0)

# 画线
center_y = 512 // 2
start_pos = (0, center_y)
end_pos = (512, center_y)

cv2.line(img, start_pos, end_pos, (0, 255, 0), 5)

cv2.imshow("image", img)
cv2.waitKey(0)

cv2.destroyAllWindows()

打开摄像头代码:

02_opencv_camera.py:

python 复制代码
import cv2

capture = cv2.VideoCapture(0)

if not capture.isOpened():
    print("Error: Camera not found")
    exit()

while True:
    ret, frame = capture.read()
    if not ret:
        print("Error: Failed to capture frame")
        break

    # 这里的frame.shape假定 : (480, 640, 3)
    origin_with = frame.shape[1]  # row, 即高度
    origin_height = frame.shape[0]  # col, 即宽度

    frame = cv2.resize(frame, (origin_with // 2, origin_height // 2))

    cv2.imshow("Camera", frame)
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break


capture.release()
cv2.destroyAllWindows()

这里解释一下:

cv2.waitKey(1) 是 OpenCV 中用于等待键盘输入的函数,括号中的数字表示等待的毫秒数。

如果有按键,返回按键的 ASCII 码

相关推荐
HIT_Weston11 小时前
45、【Agent】【OpenCode】本地代理分析(请求&接收回调)
人工智能·agent·opencode
知行合一。。。12 小时前
Python--04--数据容器(总结)
开发语言·python
架构师老Y12 小时前
008、容器化部署:Docker与Python应用打包
python·容器·架构
逻辑君12 小时前
认知神经科学研究报告【20260010】
人工智能·深度学习·神经网络·机器学习
星河耀银海12 小时前
远控体验分享:安全与实用性参考
人工智能·安全·微服务
lifewange12 小时前
pytest-类中测试方法、多文件批量执行
开发语言·python·pytest
企业架构师老王12 小时前
2026企业架构演进:科普Agent(龙虾)如何从“极客玩具”走向实在Agent规模化落地?
人工智能·ai·架构
GreenTea12 小时前
一文搞懂Harness Engineering与Meta-Harness
前端·人工智能·后端
pluvium2712 小时前
记对 xonsh shell 的使用, 脚本编写, 迁移及调优
linux·python·shell·xonsh
鬼先生_sir13 小时前
Spring AI Alibaba 1.1.2.2 完整知识点库
人工智能·ai·agent·源码解析·springai