OpenCV-Python之 Numpy数组操作

Numpy介绍:

NumPy is the fundamental package for scientific computing with Python. It contains among other things:

  • a powerful N-dimensional array object
  • sophisticated (broadcasting) functions
  • tools for integrating C/C++ and Fortran code
  • useful linear algebra, Fourier transform, and random number capabilities

官网访问:http://www.numpy.org/

Numpy

遍历数组中的每个像素点

修改数组中像素点的值

data\dtype\size\shape\len

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import cv2 as cv
import numpy as np


def access_pixels(image):
    print(image.shape)
    height = image.shape[0]
    width = image.shape[1]
    channels = image.shape[2]
    #读取高度、宽度、通道数
    print("width:%s,height:%s channels:%s"%(width, height, channels))
    #遍历每个像素点,即numpy访问每个像素点
    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
    cv.imshow("pixels_demo", image)


src = cv.imread("F:\\flower.jpg")#图片的位置路径
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
t1 = cv.getTickCount()
access_pixels(src)
t2 = cv.getTickCount()
time =(t2-t1)/cv.getTickFrequency()
print("time: %s ms"%(time*1000))
cv.waitKey(0)
cv.destroyAllWindows()
运行结果如图:



创建一张新图片,访问多通道:

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
import cv2 as cv
import numpy as np


#创建一张新的图像
def create_pic():
    pic = np.zeros([400, 400, 3], np.uint8) #创建一个3通道,第一个参数是形状,第二个是类型
    #修改第一个通道
    # pic[:, :, 1] = np.ones([400, 400])*255 #绿色
    pic[:, :, 2] = np.ones([400, 400]) * 255 #红色
    cv.imshow("new pic", pic)

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

运行结果如下图:


访问单通道:

  #访问单通道
    pic = np.zeros([400, 400, 1], np.uint8)
    # pic[ : , :, 0] = np.ones([400, 400]) *127 #灰色
    # pic = pic * 0  #黑色
    pic = pic * 255  
    cv.imwrite("F:\\flower111.jpg", pic) #保存

    cv.imshow("new pic", pic)

猜你喜欢

转载自blog.csdn.net/elegentbeauty/article/details/80085521