计算机视觉之图像特效(实现图像灰度处理等功能)(待更新。。。)

1.图像灰度处理

下面介绍四种图像灰度处理的方法:

方法1:cv2中的imread(参数:0表示为灰度图片,1表示为彩色图片)

测试代码如下:

1 import cv2
2 # 方法1 imread
3 img0 = cv2.imread('image0.jpg', 0)  # 0 为灰度图片 1 为彩色图片
4 img1 = cv2.imread('image0.jpg', 1)
5 print(img0.shape)
6 print(img1.shape)
7 cv2.imshow('src0',img0)
8 cv2.imshow('src1',img1)
9 cv2.waitKey(0)

运行结果如下:

src0为灰度图像:

src1为彩色图像:

方法 2:cvtColor

测试代码如下:

1 # 方法2 cvtColor
2 import cv2
3 img = cv2.imread('image0.jpg', 1)
4 dst = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 完成颜色空间的转换 从bgr模式转化为灰度模式
5 cv2.imshow('dst', dst)
6 cv2.waitKey(0)

运行结果如下:

同样的可以转化为灰度图像:

方法3:对RGB三个分量取均值

 1 # 方法3 RGB R=G=B gray=(R+G+B)/3
 2 import cv2
 3 import numpy as np
 4 img = cv2.imread('image0.jpg', 1)
 5 cv2.imshow('src',img)
 6 imgInfo = img.shape
 7 height = imgInfo[0]
 8 width = imgInfo[1]
 9 dst = np.zeros((height,width,3),np.uint8)
10 for i in range(0,height):
11     for j in range(0,width):
12         (b,g,r) = img[i,j]
13         gray = (int(b)+int(g)+int(r))/3  # 防止数据溢出
14         dst[i,j] = np.uint8(gray)
15 cv2.imshow('dst',dst)
16 cv2.waitKey(0)

 运行结果:略

方法4:对rbg加权 gray = r*0.299+g*0.587+b*0.114

 1 # 方法4 对rbg加权
 2 # gray = r*0.299+g*0.587+b*0.114
 3 import cv2
 4 import numpy as np
 5 img = cv2.imread('image0.jpg', 1)
 6 cv2.imshow('src',img)
 7 imgInfo = img.shape
 8 height = imgInfo[0]
 9 width = imgInfo[1]
10 dst = np.zeros((height,width,3),np.uint8)
11 w = [0.299, 0.587, 0.114]
12 for i in range(0,height):
13     for j in range(0,width):
14         (b,g,r) = img[i,j]
15         gray = r*0.299+g*0.587+b*0.114
16         dst[i,j] = np.uint8(gray)
17 cv2.imshow('dst',dst)
18 cv2.waitKey(0)

 运行结果:略

图像转灰度算法优化:

原因:

  • 重要
  • 基础 
  • 实时性

优化方法:

  • 定点运算优于浮点运算
  • 减法优于乘除
  • 移位运算优于乘除

测试代码如下:

 1 import cv2
 2 import numpy as np
 3 img = cv2.imread('image0.jpg', 1)
 4 cv2.imshow('src',img)
 5 imgInfo = img.shape
 6 height = imgInfo[0]
 7 width = imgInfo[1]
 8 dst = np.zeros((height,width,3),np.uint8)
 9 for i in range(0,height):
10     for j in range(0,width):
11         (b,g,r) = img[i,j]
12         b = int(b)
13         g = int(g)
14         r = int(r)
15         # gray = (int(b) + int(g) + int(r)) / 3  # 防止数据溢出
16         gray = (r+(g << 1)+b) >> 2  # 浮点转化成了定点 r和b乘以1省略掉 乘除转化为移位运算 但是会损失一点精度
17         dst[i,j] = np.uint8(gray)
18 cv2.imshow('dst',dst)
19 cv2.waitKey(0)

运行结果如下:

src为彩色的原始图像:

dst为转化为灰度的目标图像:

其实可以通过算法优化的图像对比前面四种方法处理后的图像,可以知道,其实效果都差不多,但是性能显著提升!

猜你喜欢

转载自www.cnblogs.com/shixinzei/p/10895806.html