计算机视觉:图片的灰度处理和颜色反转
Posted il_持之以恒_li
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了计算机视觉:图片的灰度处理和颜色反转相关的知识,希望对你有一定的参考价值。
1.灰度处理
1.1 方法1
还记得我的这篇博客的这个注释吗?
也就是方法cv2.imread(),里面有两个参数,第一个参数为图片的路径,第二个参数为是否为彩色图片,如果把第二个参数改为0,会怎么样呢?
import cv2
# 方法1
img = cv2.imread(filename='../anqila21.jpg',flags=0)
cv2.imshow('demo',img)
cv2.waitKey(0)
1.2 方法2
import cv2
# 方法2
img = cv2.imread(filename='../anqila21.jpg',flags=1)
dst = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow('demo',dst)
cv2.waitKey(0)
运行结果和上述一样
1.3 方法3 使用算法实现
import cv2
import numpy as np
# 算法实现
img = cv2.imread(filename='../anqila21.jpg',flags=1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
dst = np.zeros((height,width,3),np.uint8)
for i in range(height):
for j in range(width):
(b,g,r) = img[i,j]
# gray = (int(b)+int(g)+int(r))/3 # 灰度值
# dst[i,j] = np.uint8(gray)
gray = 0.299*int(r)+0.587*int(g)+0.114*int(b) # 灰度值
dst[i,j] = np.uint8(gray)
cv2.imshow('demo',dst)
cv2.waitKey(0)
2. 图片的颜色反转
2.1 灰度图片的颜色反转
import cv2
import numpy as np
img = cv2.imread(filename='../anqila21.jpg',flags=0)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
dst = np.zeros((height,width),np.uint8)
for i in range(height):
for j in range(width):
gray = img[i,j]
dst[i,j] = 255-gray
cv2.imshow('dst',dst)
cv2.waitKey(0)
2.2 彩色图片的颜色反转
import cv2
import numpy as np
img = cv2.imread(filename='../anqila21.jpg',flags=1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
dst = np.zeros((height,width,3),np.uint8)
for i in range(height):
for j in range(width):
(b,g,r) = img[i,j]
dst[i,j] = (255-b,255-g,255-r)
cv2.imshow('dst',dst)
cv2.waitKey(0)
以上是关于计算机视觉:图片的灰度处理和颜色反转的主要内容,如果未能解决你的问题,请参考以下文章