numpy - f numpy 数组的字符串格式

标签 numpy formatting pixel

这是我的代码片段。它打印图像像素的平均值和标准偏差。

from numpy import asarray
from PIL import Image
import os

os.chdir("../images") 
image = Image.open("dubai_2020.jpg")
pixels = asarray(image) 
pixels = pixels.astype("float32")
means, stds = pixels.mean(axis=(0, 1), dtype="float64"), pixels.std(
    axis=(0, 1), dtype="float64")
print(f"Means: {means:%.2f}, Stds: {stds:%.2f} ")

输出是
 File "pil_local_standard5.py", line 15, in <module>
    print(f"Means: {means:%.2f, %.2f, %.2f}, Stds: {stds:%.2f, %.2f, %.2f} ")

TypeError: unsupported format string passed to numpy.ndarray.__format__

在这种情况下,如何定义数据的 f 字符串格式?

最佳答案

不幸的是,Python 的 f-string 不支持 numpy 数组的格式。

解决方法 我想出了:

def prettifyStr(numpyArray, fstringText):
  num_rows = numpyArray.ndim
  l = len(str(numpyArray))
  t = (l // num_rows)
  diff_to_center_align = 50 - t
  return f"{str(numpyArray)}{' ': <{diff_to_center_align}}{fstringText}"
sample 使用
    print( prettifyStr(a2, "this is some text") )
    print( prettifyStr(a3, "this is some text") )
    print( prettifyStr(a1, "this is some text") )
    print( prettifyStr(a4, "this is some text") )
输出
[[0.  3.  4. ]
 [0.  5.  5.1]]                                   this is some text 

[[0.   3.   4.   4.35]
 [0.   5.   5.1  3.6 ]]                           this is some text 

[[0 3]
 [0 5]]                                           this is some text 

[[0.   3.   4.   4.35 4.25]
 [0.   5.   5.1  3.6  3.1 ]]                      this is some text

关于numpy - f numpy 数组的字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60199696/

相关文章:

python - SciPy/NumPy : Normalize a csr_matrix

python - 狮身人面像浮点格式

Java 货币格式化程序向负值添加括号

c++ - 如何删除在 C++ 中使用 setw 时创建的额外空间?

Java:从缓冲图像中获取 RGBA 作为整数数组

c - 读取屏幕的一个像素(即您现在可以看到的 1024*768)

java - 缩放表示像素的字节数组的函数

python - 更新 numpy 数组中的值时修复代码重复

python - 查找框和裁剪图像的角点

python - 在python中打开文本文件作为数组或列表列表