• 图像灰度处理


    这里采用四种方法对图像进行灰度处理:

    方法一:读取图片时只读取灰度图像

    方法二:调用opencv Api实现

    方法三:算法实现图像灰度:gray = (B + G + R)/3

    方法四:算法实现:gray = r*0.299 + g*0.587 + b*0.114

    代码:

    import cv2
    import numpy as np
    gray1 = cv2.imread('D:/pythonob/imageinpaint/img/zidan.jpg',0)#方法一
    imgSrc = cv2.imread('D:/pythonob/imageinpaint/img/zidan.jpg',1)
    gray2 = cv2.cvtColor(imgSrc,cv2.COLOR_BGR2GRAY)#方法二:API实现图像灰度。第二个参数:转换方式BGR-->gray
    #方法三;算法实现图像灰度:gray = (B + G + R)/3
    imgInfo = imgSrc.shape
    height = imgInfo[0]
    width = imgInfo[1]
    gray3 = np.zeros((height,width,3),np.uint8)
    for i in range(0,height):
    for j in range(0,width):
    (b,g,r) = imgSrc[i,j]
    gray = (int(b) + int(g) + int(r))/3
    gray3[i,j] = np.uint8(gray)
    #方法四:gray = r*0.299 + g*0.587 + b*0.114
    #优化:定点运算速度大于浮点运算速度,+-运算速度大于*/运算速度
    #上式可以改为gray = (r*1 + g*2 + b*1)/4 即先乘四,再除以四(精度不高)可以改为乘以10,100,1000,10000等等
    #进一步用移位表示:修改为-->gray = (r + (g<<1) + b)>>2 g*2即g左移一位,整体*4即整体右移2位
    gray4 = np.zeros((height,width,3),np.uint8)
    for i in range(0,height):
    for j in range(0,width):
    (b,g,r) = imgSrc[i,j]
    gray = int(b)*0.114 + int(g)*0.587 + int(r)*0.299
    gray4[i,j] = np.uint8(gray)
    cv2.imshow('G1',gray1)
    cv2.imshow('imgSrc',imgSrc)
    cv2.imshow('G2',gray2)
    cv2.imshow('G3',gray3)
    cv2.imshow('G4',gray4)
    cv2.waitKey(0)

    效果图:

     

  • 相关阅读:
    修改图片大小 分辨率
    Tools
    写log
    4Sum
    3Sum Closest
    避免调试时加载符号
    SDN期末作业——负载均衡
    SDN第五次上机作业
    个人作业——软件工程实践总结作业
    SDN第四次作业
  • 原文地址:https://www.cnblogs.com/cxxBoo/p/11452398.html
Copyright © 2020-2023  润新知