import numpy as np
import matplotlib.pyplot as plt
import cv2
import time
img = cv2.imread('lena.jpg',0)
# 以遍历每个像素取反为例
# 方法1
t1 = time.time()
img1 = np.copy(img)
rows,cols = img1.shape[:2]
for row in range(rows):
for col in range(cols):
img[row,col] = 255 - img[row,col]
t2 = time.time()
print('方法1所需时间:',t2-t1)
# 方法2
t3 = time.time()
img2 = np.copy(img)
rows,cols = img2.shape[:2]
img2 = img2.reshape(rows*cols)
# print(img2)
for i in range(rows*cols):
img2[i] = 255-img2[i]
img2 = img2.reshape(rows,cols)
# print(img2)
t4 = time.time()
print('方法2所需时间:',t4-t3)
# 方法3
t5 = time.time()
img3 = np.copy(img)
# 使用多维迭代生成器
for (x,y), pixel in np.ndenumerate(img3):
img3[x,y] = 255-pixel
t6 = time.time()
print('方法3所需时间:',t6-t5)
测试结果:
方法1所需时间: 0.14431977272033691
方法2所需时间: 0.13863205909729004
方法3所需时间: 0.24196243286132812
来源:CSDN
作者:陨星落云
链接:https://blog.csdn.net/qq_28368377/article/details/104588734