Python 调用 OpenCV 配置指南与基础绘图操作

林见深
林见深
发布时间:2026-10-13 | 5人浏览过
原创

本文详解在 Anaconda 环境中配置 OpenCV 的方法,涵盖路径设置与 pip 安装技巧。重点解析图像读取、BGR 与 RGB 颜色空间转换机制,以及利用 cv2 模块绘制直线、矩形、圆形、多边形和添加文字的具体参数与代码实现,附带像素值获取与图像切片操作示例。

一、在 Anaconda2 中配置 OpenCV

解压 OpenCV 安装包后,需添加系统环境变量。具体路径为:右键点击“计算机”选择“属性”,进入“高级系统设置”,点击“环境变量”,在“系统变量”中找到并编辑“Path”,添加路径 F:\Program Files (x86)\opencv-3.2.0-vc14\build\x64\vc14\bin。

将 opencv/build/python/2.7/x64 目录下的 cv2.pyd 文件拷贝至 Anaconda2/Lib/Site-packages/ 目录下。

注意:从路径中的 python/2.7 可以看出,OpenCV 官方提供的 Python 接口仅支持 Anaconda2 版本。若使用的是 Anaconda3,可通过命令行执行 conda install -c https://conda.anaconda.org/menpo opencv3 进行安装。

也可参考相关文档完成 Anaconda3 的配置流程。

配置完成后,打开 ipython 进行功能测试。

import cv2
print(cv2.__version__)

二、OpenCV 基础知识

1. 读取、显示和写入图像

import cv2
import matplotlib.pyplot as plt
# 读取图像,第二个参数可以为1(默认读入彩图, 可省略), 0(以灰度图读入)
im = cv2.imread('empire.jpg', 1) # 函数imread()返回图像为一个标准的 NumPy 数组
h,w = im.shape[:2]
print h,w
# 显示图像,第一个参数是窗口的名字,其次才是我们的图像,窗口会自动调整为图像大小。
cv2.imshow('image', img)
cv2.waitKey(0) # 为防止图像一闪而过,无限期的等待键盘输入
cv2.destroyAllWindows() # 关闭所有图像
# 保存图像(必须设置保存图像的路径和扩展名)
cv2.imwrite('result.png', im)
# 使用 plt 显示图像(可显示像素坐标及像素值)、保存图像
plt.imshow(im, cmap='gray', interpolation='bicubic')
plt.show()
plt.savefig('figpath.png', bbox_inches='tight')

2. 颜色空间转换

在 OpenCV 中,图像并非按传统的 RGB 颜色通道存储,而是采用 BGR 顺序(即 RGB 的倒序)。读取图像时默认格式为 BGR,但可通过转换函数调整。颜色空间转换可使用 cv2.cvtColor() 函数实现。

# 1.使用opencv读取并创建灰度图像,按 BGR 顺序
im = cv2.imread('empire.jpg')
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
# 2.使用matplotlib.image 读入并创建灰度图像,按 RGB 顺序
import matplotlib.image as mpl_img
im = mpl_img.imread('empire.jpg')
gray = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
# Note: 注意1和2的区别在颜色转换代码
# 常用:cv2.COLOR_BGR2RGB、cv2.COLOR_GRAY2BGR、cv2.COLOR_BGR2HSV

3. 在图像上绘制直线、矩形、圆、多边形(曲线)

绘制直线使用 cv2.line() 函数。

import cv2
# 读取图像,按 BGR 顺序
img = cv2.imread('empire.jpg')
# 传入图像、起点坐标、终点坐标、线的颜色(color)、线的厚度(thickness)
# color : Color of the shape. for BGR, pass it as a tuple, eg: (255,0,0) for blue. For grayscale, just pass the scalar value.
# thickness : if -1 is passed for closed figures like circles, it will fill the shape, default thickness = 1.
img = cv2.line(img, (0, 0), (511, 511), (255, 0, 0), 5)

绘制矩形使用 cv2.rectangle() 函数。

# 需要传入图像、左上角顶点坐标、右下角顶点坐标、颜色、线宽
img = cv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 3)

绘制圆形使用 cv2.circle() 函数。

# 需要传入图像、圆的中心点坐标、半径、颜色、线宽
img = cv2.circle(img, (447, 63), 63, (0, 0, 255), -1)
# If -1 is passed for closed figures like circles, it will fill the shape. default thickness = 1

绘制多边形(含曲线)使用 cv2.polylines() 函数。

# 数组的数据类型必须为int32,若知道曲线方程,可以生成一堆点,就可以画出曲线来啦
pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)
# 第一个参数为-1, 表明这一维的长度(点的数量)是根据后面的维度的计算出来的
pts = pts.reshape((-1,1,2))
# 如果第三个参数是False,我们得到的多边形是不闭合的(首尾不相连)
img = cv2.polylines(img, [pts], True, (0, 255, 255))

在图片上添加文字使用 cv2.putText() 函数。

font = cv2.FONT_HERSHEY_SIMPLEX
# 第 3~6 个参数为:bottom-left corner where data starts、font size、color、thickness
cv2.putText(img,'OpenCV',(10,500), font, 4, (255, 255, 255), 2, cv2.LINE_AA)

4. 图像的基础操作

获取并修改像素值

import cv2
import numpy as np
img = cv2.imread('messi5.jpg')
px = img[100, 100]
print px
[57 63 68]
# accessing only blue pixel
blue = img[100, 100, 0]
print blue
57 
# modify the pixel
img[100, 100] = [255, 255, 255]
print img[100, 100]
[255 255 255]
# channel 2 所有值置为0 
img[:, :, 2] = 0

获取图像属性

img = cv2.imread('messi5.jpg')
print img.shape
(960L, 1280L, 3L)
print img.size
3686400
print img.dtype
uint8

选取图像块

img = cv2.imread('messi5.jpg')
# select the ball and copy it to another region
ball = img[280:340, 330:390] # 注意:340和390取不到
img[273:333, 100:160] = ball

以上通过 Python 接口使用 OpenCV 的方法即为全部内容,供读者参考与支持。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表