这次给大家带来Python接口使用OpenCV的方法,Python接口使用OpenCV的注意事项有哪些,下面就是实战案例,一起来看一下。
一、在 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 的话,可以打开cmd,然后执行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,但是还有一些可用的转换函数。颜色空间的转换可以用函数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
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
以上是Python接口使用OpenCV的方法的详细内容。更多信息请关注PHP中文网其他相关文章!

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造

数组的同质性对性能的影响是双重的:1)同质性允许编译器优化内存访问,提高性能;2)但限制了类型多样性,可能导致效率低下。总之,选择合适的数据结构至关重要。

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,内存效率段

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

Atom编辑器mac版下载
最流行的的开源编辑器

WebStorm Mac版
好用的JavaScript开发工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能