OpenCV图像颜色反转算法

前言

图像颜色的反转,比较简单的思路就是使用255减去当前值,从而得到反转后的图像.原始图片:
OpenCV图像颜色反转算法_第1张图片

1.灰度图像的颜色反转

import cv2
import numpy as np

# 灰度 0-255 255-当前灰度值
img = cv2.imread('image0.jpg', 1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

dst = np.zeros((height, width, 1), np.uint8)

for i in range(height):
    for j in range(width):
        grayPixel = 255 - gray[i, j]
        dst[i, j] = grayPixel

cv2.imshow('image', dst)
cv2.waitKey(0)

用255减去当前灰度值,得到反转后的图像.图像如下:
OpenCV图像颜色反转算法_第2张图片

2.BGR图像的反转

import cv2
import numpy as np

img = cv2.imread('image0.jpg', 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]
        b = 255 - b
        g = 255 - g
        r = 255 - r
        dst[i, j] = (b, g, r)


cv2.imshow('image', dst)
cv2.waitKey(0)

BGR图像反转也是一样,同样是使用255减去每一个通道的当前值.效果如下:
OpenCV图像颜色反转算法_第3张图片

你可能感兴趣的:(opencv)