【问题标题】:Gradual conversion of image to greyscale with numpy in python在python中使用numpy将图像逐渐转换为灰度
【发布时间】:2020-04-16 05:34:37
【问题描述】:

假设我有一张图片,我想让它在一定距离内淡出为灰度。

我已经知道要使用 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

我确实得到了我希望的淡入淡出行为,但据我所知,它只是淡入绿色通道,同时对红色和蓝色进行了核对。

所以,例如:

变成

这是正确的转换行为,但会逐渐变为绿色而不是灰度...

【问题讨论】:

  • 作为一个完全无关的,创建初始坐标数组作为一个循环非常慢。如果有人能够描述如何在 Numpy 中完全形成,我将不胜感激。我以为 np.fromfunction(lambda x, y: (x, y), self.image.shape[:-1], dtype= 'int') 会这样做,但它的行为与我预期的不同。
  • 创建初始坐标数组作为一个循环非常慢。 那是哪个数组,transform_weighter?顺便说一句,变量和函数名称通常应遵循lower_case_with_underscores 样式。
  • 我的意思是我想要[[(0,0), (1, 0), (2, 0), ...], [(0,1), (1,1), (2,1), ...], ...] 的数组。此外,蛇案很糟糕,唯一更糟糕的是没有分离词哈哈。低开始骆驼大写和大写类的 java/script 约定更清晰,IMO 也不那么令人眼花缭乱。

标签: python arrays numpy image-processing


【解决方案1】:

嗯,答案既简单又困难。

我的问题的前提存在根本缺陷。在answers.opencv.org 上引用这个答案:

首先,您必须了解不存在灰度的 MxNx3。我的意思是,灰度的概念是你有一个通道来描述黑白之间渐变的强度。因此,目前尚不清楚为什么需要 3 通道灰度图像,但如果需要,我建议您获取 1 通道灰度图像的每个像素的值,然后将其复制 3 次,每个通道一个BGR 图像。当 BGR 图像在每个通道上具有相同的值时,它看起来是灰色的。

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

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

【讨论】:

    猜你喜欢
    • 2018-12-19
    • 1970-01-01
    • 2021-11-24
    • 2018-11-28
    • 2021-06-06
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多