【发布时间】: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 矩阵(其中N 和M 是图像的维度),这个矩阵是一个带有红色变换、绿色变换和蓝色变换的维度。
所以,对于给定的“保持颜色”的原点和半径,我有
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