gpt4 book ai didi

python - 如何使用 numpy.where 更改图像的所有像素?

转载 作者:行者123 更新时间:2023-12-01 01:45:43 24 4
gpt4 key购买 nike

我有一个形状为 (300,300,3) 的图像,由这些像素组成 [255, 194, 7],[224, 255, 8],[230, 230, 230],[11, 102, 255]。我想将此像素 [230, 230, 230] 更改为 [255,255,255]。将其他像素保留到[0,0,0]。所以我应用 numpy where 函数来切换像素。下面是代码:

import numpy

im = numpy.array([[[255, 194, 7],[224, 255, 8],[230, 230, 230],[11, 102, 255]]])

im[np.where((im == [230, 230, 230]).all(axis = 2))] = [255,255,255]
im[np.where((im != [255,255,255]).all(axis = 2))] = [0,0,0]

第一个代码工作正常,但所有包含 255 的像素(例如 [11, 102, 255])在第二行中根本不会翻转。并且图像保持不变。谁能告诉我我做错了什么?

最佳答案

import numpy as np
im = np.array([[[255, 194, 7],[224, 255, 8],[230, 230, 230],[11, 102, 255]]])

像这样吗?
制作一个掩码并用它来更改值。

>>> mask = im == 230
>>> im[mask] = 255
>>> im[np.logical_not(mask)] = 0

>>> im
=> array([[[ 0, 0, 0],
[ 0, 0, 0],
[255, 255, 255],
[ 0, 0, 0]]])

或者使用 numpy.where

>>> np.where(im==230, 255, 0)

=> array([[[ 0, 0, 0],
[ 0, 0, 0],
[255, 255, 255],
[ 0, 0, 0]]])

关于python - 如何使用 numpy.where 更改图像的所有像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51367545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com