【问题标题】:How can I save an image with negative pixel values in python?如何在 python 中保存具有负像素值的图像?
【发布时间】:2020-06-16 19:12:18
【问题描述】:

在您开始阅读之前,我想向您道歉;我是 Python 新手,如果这个问题看起来很简单,我很抱歉。

我正在尝试获取我拥有的一组图像并将它们归一化以用于深度网络训练(将图像的每个像素除以标准偏差,然后减去像素的平均值),然后保存使用 Python 分别生成图像。我已经能够编写使图像标准化的代码,但我的问题在于保存图像,因为它们具有负像素值。

我看过 this question 并阅读了答案,但我的问题是用户 Swaroop 在 cmets 中提到的问题。提供的答案不适用于我使用的图像类型(具有三个通道或“RGB”的图像)

这是我的全部代码:

import matplotlib.pyplot as plt
import numpy as np
import copy
import math
from PIL import Image

# Setup Important Variables
basic_path = 'Censored_for_privacy_reasons'
mins = 0

# Setup Standard Deviation Function
def stDevImage(imageArray, plane):
    stDevArray = []
    stDevAdd = 0
    for row in range(0,imageArray.shape[0]):
        for column in range(0,imageArray.shape[1]):
            stDevArray.append(copy.deepcopy(imageArray[row][column][plane]))
    meanForArray = np.mean(stDevArray)
    for pixelValue in range(0,len(stDevArray)):
        stDevAdd += pow(stDevArray[pixelValue]-meanForArray,2)
    stDev = math.sqrt(stDevAdd/len(stDevArray))
    return [stDev, meanForArray]

img = plt.imread(basic_path+'25/NS0/NS0_1.png')
imgArray = np.asarray(img)
normImage = copy.deepcopy(imgArray)

rPlaneSt = stDevImage(imgArray, 0)
gPlaneSt = stDevImage(imgArray, 1)
bPlaneSt = stDevImage(imgArray, 2)
for row in range(0, imgArray.shape[0]):
    for column in range(0,imgArray.shape[1]):
        normImage[row][column][0] = copy.deepcopy(normImage[row][column][0]/rPlaneSt[0]-rPlaneSt[1])
        normImage[row][column][1] = copy.deepcopy(normImage[row][column][1]/gPlaneSt[0]-gPlaneSt[1])
        normImage[row][column][2] = copy.deepcopy(normImage[row][column][2]/bPlaneSt[0]-bPlaneSt[1])
        if normImage[row][column][0] < mins:
            mins = copy.deepcopy(normImage[row][column][0])
imgFinal = Image.fromarray(normImage, 'I')
imgFinal.save("/Users/Censored/Desktop/test.tif")

标记为stDevImage 的函数是提供其接收图像中平面标准差​​的函数。它返回该平面的标准差和平均值。

正如您在代码的最后两行中看到的那样,我正在尝试上述问题的答案所说的内容,但无济于事。

这是代表我正在使用的图像类型的图像(它也是代码中读取 img = plt.imread(basic_path+'25/NS0/NS0_1.png') 的行中引用的图像)。

The image is located here

我们将不胜感激任何和所有的帮助!

【问题讨论】:

  • 使用 tifffile 模块,或 OpenCV cv2.imwrite()wandlibvipsimageio 编写一个 3 通道浮点 TIFF。跨度>
  • 您可以使用 np.save 将其保存为 numpy 数组
  • @MarkSetchell 感谢您的评论。这实际上对我有用。如果您可以将其写为答案,那就太好了,因此我可以将其标记为已解决。感谢您的帮助!
  • 这里时间不早了……我明天再做。很高兴它有效。

标签: python image image-processing


【解决方案1】:

我建议您尝试使用以下软件包在 Python 中访问浮点 TIFF 文件:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 2022-01-20
    • 2022-07-11
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 2020-12-21
    相关资源
    最近更新 更多