Skip to content

Files

Latest commit

b03d156 · Nov 20, 2019

History

History
104 lines (68 loc) · 1.88 KB

99.md

File metadata and controls

104 lines (68 loc) · 1.88 KB

图像数据和操作

原文: https://pythonspot.com/image-data-and-operations/

OpenCV(cv2)可用于从图像中提取数据并对其进行操作。 我们在下面演示一些示例:

图像属性

我们可以使用以下代码提取宽度,高度和颜色深度:

import cv2
import numpy as np

# read image into matrix.
m =  cv2.imread("python.png")

# get image properties.
h,w,bpp = np.shape(m)

# print image properties.
print "width: " + str(w)
print "height: " + str(h)
print "bpp: " + str(bpp)

访问像素数据

我们可以直接使用矩阵访问图像的像素数据,例如:

import cv2
import numpy as np

# read image into matrix.
m =  cv2.imread("python.png")

# get image properties.
h,w,bpp = np.shape(m)

# print pixel value
y = 1
x = 1
print m[y][x]

要遍历图像中的所有像素,可以使用:

import cv2
import numpy as np

# read image into matrix.
m =  cv2.imread("python.png")

# get image properties.
h,w,bpp = np.shape(m)

# iterate over the entire image.
for py in range(0,h):
for px in range(0,w):
print m[py][px]

图像处理

您可以直接修改像素和像素通道(r, g, b)。 在下面的示例中,我们删除了一个颜色通道:

import cv2
import numpy as np

# read image into matrix.
m =  cv2.imread("python.png")

# get image properties.
h,w,bpp = np.shape(m)

# iterate over the entire image.
for py in range(0,h):
for px in range(0,w):
m[py][px][0] = 0

# display image
cv2.imshow('matrix', m)
cv2.waitKey(0)

要更改整个图像,您必须更改所有通道:m[py][px][0]m[py][px][1]m[py][px][2]

保存图像

您可以使用以下方法将修改后的图像保存到磁盘:

cv2.imwrite('filename.png',m)

下载计算机视觉示例和课程