17_图片的灰度处理

  时间:2019-01-11
本文章向大家介绍17_图片的灰度处理,主要包括17_图片的灰度处理使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
#图片的灰度处理
#方法1
import cv2
img0 = cv2.imread('ruonan.jpg',0)
img1 = cv2.imread('ruonan.jpg',1)
print(img0.shape)
print(img1.shape)
cv2.imshow('Img0',img0)
cv2.imshow('Img1',img1)
cv2.waitKey(0)
#方法二
import cv2
img = cv2.imread('ruonan.jpg',1)
dst = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)  #参数1 data 参数2 颜色空间的转换
cv2.imshow('dst',dst)
cv2.waitKey(0)
#方法3   取均值
import cv2
img = cv2.imread('ruonan.jpg',1)
Info = img.shape
height = Info[0]
width = Info[1]
dst = np.zeros((height,width,3),np.uint8)
for i in range(0,heigt):
 for i in range(0,width):
  (b,g,r) = img[i,j]
  gray = (int(b)+int(g)+int(r))/3
  dst[i,j] = np.uint8(gray)
cv2.imshow('dst',dst)
cv2.waitKey(0)
#方法 4
# gray = r*0.299+g*0.587+b*0.114
import cv2
img = cv2.imread('ruonan.jpg',1)
Info = img.shape
height = Info[0]
width = Info[1]
dst = np.zeros((height,width,3),np.uint8)
for i in range(0,heigt):
 for i in range(0,width):
  (b,g,r) = img[i,j]
  b = int(b)
  g = int(g)
  r = int(r)   #分析最后的gray是否也是int
  gray = r*0.299+g*0.587+b*0.114
  dst[i,j] = np.uint8(gray)
cv2.imshow('dst',dst)
cv2.waitKey(0)
#算法的优化
#定点运算的速度快于浮点,移位计算速度快于定点,+-快于*/
# gray = r*0.299+g*0.587+b*0.114
#gray左右同时乘以4,在除以4
#gray = (r*1+g*2+b*1)/4
import cv2
img = cv2.imread('ruonan.jpg',1)
Info = img.shape
height = Info[0]
width = Info[1]
dst = np.zeros((height,width,3),np.uint8)
for i in range(0,heigt):
 for i in range(0,width):
  (b,g,r) = img[i,j]
  b = int(b)
  g = int(g)
  r = int(r)   #分析最后的gray是否也是int
  #一次优化gray = (r*1+g*2+b*1)/4
  #二次优化 gray = (r+(g<<1)+b)>>2
  dst[i,j] = np.uint8(gray)
cv2.imshow('dst',dst)
cv2.waitKey(0)

上一页 下一页

原文地址:http://www.manongjc.com/article/42944.html