在python中使用numpy将图像逐渐转换为灰度

2024-10-01 22:30:48 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个图像,我想让它在一段距离内淡出灰度

我已经知道,要使用Numpy将图像完全转换为灰度,我会执行以下操作

import numpy as np
import cv2
myImage = cv2.imread("myImage.jpg")
grey = np.dot(an_image[...,:3], [0.2989, 0.5870, 0.1140])

这不是我要找的。我已经可以让它工作了

我有一个NxMx3矩阵(其中NM是图像的维度),这个矩阵是一个带有红色变换、绿色变换和蓝色变换的维度

所以,对于给定的原点和半径“保持这个颜色”,我有

greyscaleWeights = np.array([0.2989, 0.5870, 0.1140])
# We flip this so we can weight down the transformation
greyscaleWeightOffsets = np.ones(3) - greyscaleWeights
from scipy.spatial.distance import cdist as getDistances
transformWeighter = list()
for rowNumber in np.arange(rowCount, dtype= 'int'):
    # Create a row of tuples containing the coordinate we are at in the picture
    row = [(x, rowNumber) for x in np.arange(columnCount, dtype= 'int')]
    # Transform this into a row of distances from our in-color center
    rowDistances = getDistances(row, [self.focusOrigin]).T[0]
    # Get the transformation weights: inside of the focus radius we have no transform, 
    # outside of the pixelDistanceToFullTransform we have a weight of 1, and an even 
    # gradation in-between
    rowWeights = [np.clip((x - self.focusRadius) / pixelDistanceToFullTransform, 0, 1) for x in rowDistances]
    transformWeighter.append(rowWeights)
# Convert this into an numpy array
transformWeighter = np.array(transformWeighter)
# Change this 1-D set of weights into 3-D weights (for each color channel)
transformRGB = np.repeat(transformWeighter[:, :, None],3, axis=1).reshape(self.image.shape)
# Change the weight offsets back into greyscale weights
greyscaleTransform = 1 - greyscaleWeightOffsets * transformRGB
greyscaleishImage = self.image * greyscaleTransform

我确实得到了我所希望的淡出行为,但据我所知,它只是淡入了绿色通道,同时将红色和蓝色混合在一起

例如:

this test picture

转化为

this output

这是正确的转换行为,但褪色为绿色而不是灰度


Tags: ofthein图像importselffornp
1条回答
网友
1楼 · 发布于 2024-10-01 22:30:48

嗯,答案既简单又困难

我的问题的前提有根本性的缺陷。在answers.opencv.org中引用这一答案:

First, you must understand that a MxNx3 in greyscale doesn't exist. I mean, the concept of greyscale is that you have one channel describing the intensity on a gradual scale between black and white. So, it is not clear why would you need a 3 channels greyscale image, but if you do, I suggest that you take the value of each pixel of your 1 channel greyscale image and that you copy it three times, one on each channel of a BGR image. When a BGR image has the same value on each channel, it appears to be grey.

正确的答案是改变颜色空间,然后去饱和图像,所以

imageHSV = cv2.cvtColor(self.image, cv2.COLOR_RGB2HSV)
newSaturationChannel = saturationWeighter * imageHSV[:,:,1]
imageHSV[:,:,1] = newSaturationChannel
greyscaleishImage = cv2.cvtColor(imageHSV, cv2.COLOR_HSV2RGB)

相关问题 更多 >

    热门问题