Home Backend Development Python Tutorial Python interface using OpenCV method

Python interface using OpenCV method

Apr 09, 2018 pm 02:52 PM
opencv python method

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)
Copy after login

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')
Copy after login

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
Copy after login

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)
Copy after login
Draw a rectangle: cv2.rectangle()

# 需要传入图像、左上角顶点坐标、右下角顶点坐标、颜色、线宽
img = cv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 3)
Copy after login
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
Copy after login
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))
Copy after login
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)
Copy after login

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
Copy after login
Get image attributes

img = cv2.imread('messi5.jpg')
print img.shape
(960L, 1280L, 3L)
print img.size
3686400
print img.dtype
uint8
Copy after login
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
Copy after login
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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles