03Numpy数组操作

Numpy数组操作



一、Numpy 的包介绍

参考www.numpy.org 点击进入

二、遍历图像中的每个像素点

1、使用for循环遍历,但是一张图片很大,遍历时间非常的长

def access_pixels(image):
height = image.shape[0]
width = image.shape[1]
channels = image.shape[2]

print("width : %s, height : %s,channels :%s" % (width, height, channels))
for row in range(height):
    for col in range(width):
        for c in range(channels):
            pv = image[row, col, c]
            image[row, col, c] = 255 - pv
#res = cv2.resize(image, None, None, fx=0.1, fy=0.2, interpolation=cv2.INTER_CUBIC)
cv2.imshow('pixels_demo', res)

2、获取函数的运行时间

 
	t1 = cv2.getTickCount()
	# 获取运行时间
	creat_image()

	t2 = cv2.getTickCount()
	time = (t2-t1)/cv2.getTickFrequency()
	print("time :%s ms" % time*1000)

三、修改像素点的值

1、使用单个像素循环操作的方式

image[row, col, c] = 255 - pv
2、m = numpy.array([1,2,3],[4,5,6],int32)
m.fill(9)
产生结果:
array(
[9,9,9]
[9,9,9]
)

四、data\shape\dtype\size\len 属性

1、完整测试代码如下

import cv2
import numpy
def access_pixels(image):
    height = image.shape[0]
    width = image.shape[1]
    channels = image.shape[2]

    print("width : %s, height : %s,channels :%s" % (width, height, channels))
    for row in range(height):
        for col in range(width):
            for c in range(channels):
                pv = image[row, col, c]
                image[row, col, c] = 255 - pv
    #res = cv2.resize(image, None, None, fx=0.1, fy=0.2, interpolation=cv2.INTER_CUBIC)
    cv2.imshow('pixels_demo', res)


def creat_image():
"""
    # 生成多通道图片
    img = numpy.zeros([400, 400, 3], numpy.uint8)
    img[:, :, 0] = numpy.ones([400, 400])*255
    cv2.imshow('creat_image', img)
    cv2.imwrite("../picture/blue.png", img)
    """
    # 生成单通道图片
    img = numpy.zeros([400, 400, 1], numpy.uint8)
    img[:, :, 0] = numpy.ones([400, 400])*255
    cv2.imshow('creat_image', img)
    cv2.imwrite("../picture/white.png", img)


src = cv2.imread("../picture/1.png")
t1 = cv2.getTickCount()

# 获取运行时间
creat_image()

t2 = cv2.getTickCount()
time = (t2-t1)/cv2.getTickFrequency()
print("time :%s ms" % time*1000)

cv2.waitKey(0)
cv2.destroyAllWindows()  

2、在numpy基本学习的时候注意类型的选择(float,uint int…)以及zeros(),ones()等函数

3、在测试函数的时间后不满意,设法缩短运行时间,优化代码,调用opencv 的API或其他可行的方式

避免使用for循环
使用像素取反函数dst = cv2.bitwise_not(image)
可以大大缩短运行时间

你可能感兴趣的:(03Numpy数组操作)