使用Python和OpenCV进行图像负变换
图像亮度反转后的图像称为负片图像,其中图像的亮部显示为暗色,暗部显示为亮色。彩色图像(RGB图像)的负变换将反转,红色区域显示为青色,绿色区域显示为品红,蓝色区域显示为黄色。
在医学影像、遥感和其他一些应用中,负变换被广泛使用。它也有助于找到图像较暗区域的细节。
负变换函数为:
众所周知,8位图像的最大强度值为255,因此我们需要从每个像素中减去255(最大强度值)以生成负片图像。
s = T(r) = L – 1 – r
在本文中,我们将学习使用OpenCV Python以不同方式获得图像的负变换。
使用cv2.bitwise_not()函数
该函数计算输入数组的按位反转。以下是not()函数的语法:
cv2.bitwise_not(src[, dst[, mask]])
参数
src:输入图像数组。
dst:与输入数组大小和类型相同的输出数组(可选)。
mask:可选参数。
示例
在这个例子中,我们将反转图像数组的每个值以获得负片图像。
import cv2
# Load the image
img = cv2.imread('Images/Fruits.jpg')
# Invert the image using cv2.bitwise_not
img_neg = cv2.bitwise_not(img)
# Show the image
cv2.imshow('negative',img_neg)
cv2.waitKey(0)
输入图像

输出图像

使用减法
在这种方法中,我们使用两个for循环(基于图像尺寸)遍历像素,并从每个像素的最大像素值(255)中减去红色、绿色和蓝色的值。
示例
让我们实现一个不使用任何函数的彩色图像负变换。
import cv2
# Load the image
img = cv2.imread('Images/Fruits.jpg', cv2.COLOR_BGR2RGB)
height, width, _ = img.shape
for i in range(0, height - 1):
for j in range(0, width - 1):
# each pixel has RGB channle data
pixel = img[i, j]
# red
pixel[0] = 255 - pixel[0]
# green
pixel[1] = 255 - pixel[1]
# blue
pixel[2] = 255 - pixel[2]
# Store new values in the pixel
img[i, j] = pixel
# Display the negative transformed image
cv2.imshow('negative image', img)
cv2.waitKey(0)
输出图像

我们已成功将彩色图像转换为负片。最初,我们使用for循环迭代了图像数组的所有值(像素数据),然后从最大像素值(255)中减去每个像素值以获得负变换图像。
示例
在这里,我们将直接对最大强度值和图像数组之间应用减法运算,而不是循环遍历每个像素。
import numpy as np
import cv2
img = cv2.imread('Images/Fruits.jpg')
# Subtract the img array values from max value(calculated from dtype)
img_neg = 255 - img
# Show the negative image
cv2.imshow('negative',img_neg)
cv2.waitKey(0)
输出

对于灰度图像
对于灰度图像,在负变换中,图像的亮部显示为暗色,暗部显示为亮色。
示例
在这个例子中,我们将以灰度模式读取图像以生成其负片。
import cv2
# Load the image
gray = cv2.imread('Images/Fruits.jpg', 0)
cv2.imshow('Gray image:', gray)
# Invert the image using cv2.bitwise_not
gray_neg = cv2.bitwise_not(gray)
# Show the image
cv2.imshow('negative',gray_neg)
cv2.waitKey(0)
输入图像

输出图像

我们已经学习了使用OpenCV Python获得图像负变换的不同方法。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP