python遍历灰度图像像素方法总结

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
发布了82 篇原创文章 · 获赞 39 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_28368377/article/details/104588734