OpenCV+Python——Numpy数组操作

今天是第二课啦——Numpy数组操作

下面是一些关键代码

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("Height : %s, Width : %s, Channels : %s" % (height, width, channels))
  for row in range(height): # 开始遍历
    for col in range(width):
      for c in range(channels):
        pv = image[row, col, c] # 也可以写成 pv = image[row][col][c]
        image[row][col][c] = 255 - pv # 这里我的理解是三个通道的每个数值x都进行了运算255-x
  cv.imshow("New Image", image)


def inverse(image): # 完成与上个函数相同的功能
  dst = cv.bitwise_not(image) # 该函数是直接调用opencv库中的API,速度较自己遍历快许多许多,因为API调用的是C代码
  cv.imshow("New image", dst)
  

def create_image(): # 通过Numpy数组创建图像
  img = np.zeros([400, 400, 3], np.uint8) # 创建400*400*3的数值为0的三维数组,相当于一个RGB图像
  img[:, :, 0] = np.ones([400, 400]) * 255 # blue, green, red, 255其实表示程度,0-255程度由深至浅,因为np.ones()相当于创建的矩阵的数值为1,":"默认表示所有,添上数值后可以表示赋值范围
  cv.imshow("New Image1", img)
  img2 = np.ones([400, 400, 1], np.float32) # 创建400*400*1的数值为1的三维数组,相当于一个灰度图像,注意这里必须要写明通道数
  img2 = img2 * 127 # 相当于img[:, :, 0] = np.ones([400, 400]) * 127,可以看出若初始化使用np.ones()更方便
  cv.imshow("New Image2", img2) # 显示应为一个灰色图像
  
  m1 = np.ones([3, 3], np.float32) # 注意这里的dtype若位数不够则会被截断,比如若这里为np.uint8则显示为190
  m1.fill(1222.388) # 填充
  print(m1) # 显示应为一个数值为1222.38的3*3的矩阵
  m2 = m1.reshape([1,9]) # 若个数不等则会报错
  print(m2)
  m3 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], np.int32)
  print(m3)


src = cv.imread("/home/yangx/classroom.jpg")
cv.namedWindow("Input Image", cv.WINDOW_AUTOSIZE)
cv.imshow("Input Image", src)
t1 = cv.getTickCount() # 该函数可得到从某一时刻到该函数的时钟周期数
access_pixels()
t2 = cv.getTickCount() 
time = (t2 - t1)/cv.getTickFrequency() # 计算函数access_pixels经过的时间(cv.getTickFrequency()表示1s的时钟周期数),可知遍历像素所带来的时间开销较大,耗费处理器资源
print("Time : %s ms" % (time * 1000)) # 这里发现若写为print("Time : %s ms" % time * 1000)则会输出1000次,若写为print("Time : %s ms" % time) * 1000则会报错
create_image()
cv.waitKey(0)

cv.destroyAllWindows()  

整理:

Python格式化输出——

  • 输出字符串

  • 输出整数

  • 输出浮点数

  • 输出指定小数位数的浮点数

  • 输出指定位宽(默认右对齐)

  • 输出指定位宽(左对齐)

  • 输出指定位宽(添0)

  • 科学计数法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值