search
HomeBackend DevelopmentPython TutorialPython interface using OpenCV method

Python interface using OpenCV method

Apr 09, 2018 pm 02:52 PM
opencvpythonmethod

This time I will bring you how to use OpenCV with the Python interface. What are the precautions for using OpenCV with the Python interface? The following is a practical case, let’s take a look.

1. Configure OpenCV in Anaconda2

Decompress opencv, add system environment variables, computer-->right-click properties--> Advanced system settings-->Environment variables-->

System variables-->Edit path-->Add F:\Program Files (x86)\opencv-3.2.0-vc14\build \x64\vc14\bin

Copy opencv/build/python/2.7/x64/cv2.pyd to Anaconda2/Lib/Site-packages/

Note: You can see it from python/2.7 above It turns out that the official python interface of opencv only supports the Anaconda2 version. If you are installing Anaconda3, you can open cmd and then execute conda install -c https://conda.anaconda.org/menpo opencv3;

You can also refer to this article to configure Anaconda3

Open ipython and test it

import cv2
print(cv2.version)

2. Basic knowledge of OpenCV

1. Reading, displaying and writing images

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. Color space conversion

In OpenCV, images It is not stored in traditional RGB color channels, but in BGR order (that is, the reverse order of RGB). The default when reading images is BGR, but there are some conversion functions available. Color space conversion can be achieved using the function 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. Draw straight lines, rectangles, circles, polygons (curves) on the image

Draw straight lines: 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)
Draw a rectangle: cv2.rectangle()

# 需要传入图像、左上角顶点坐标、右下角顶点坐标、颜色、线宽
img = cv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 3)
Draw a circle: 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
Draw a polygon (including curves): 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))
In Add text to the image: 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. Basic operations of the image

Get and modify the pixel value

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
Get image attributes

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

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
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Python opencv detects and extracts the target color

How does Python write the data in the data frame to the database

The above is the detailed content of Python interface using OpenCV method. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)