有若干图像,进行读取,转为二维数组,将图片像素值归一化到0~1
时间: 2024-04-30 20:23:34 浏览: 15
之间,并将其保存为numpy数组。
以下是一个Python示例代码:
```python
import numpy as np
from PIL import Image
# 读取图像并转为灰度图
image = Image.open('image.jpg').convert('L')
# 将图像转为二维数组
data = np.array(image)
# 将像素值归一化到0~1之间
data = data / 255.0
# 将数组保存为numpy数组
np.save('image.npy', data)
```
这里使用了PIL库来读取图像,并将其转为灰度图。然后使用numpy库将图像转为二维数组,并将像素值归一化到0~1之间。最后使用numpy的save函数将数组保存为npy文件。
相关问题
有若干图像,进行读取,转为二维数组,将图片像素值归一化到0~1,改变图片尺寸为 [N, C, H, W],,获取图像一维标签
,最终返回由图像二维数组和对应标签组成的数据集。
以下是Python代码示例:
```python
import os
import numpy as np
from PIL import Image
def read_images(data_path, img_size):
images = []
labels = []
for foldername in os.listdir(data_path):
folderpath = os.path.join(data_path, foldername)
if os.path.isdir(folderpath):
for filename in os.listdir(folderpath):
if filename.endswith(".jpg"):
filepath = os.path.join(folderpath, filename)
img = Image.open(filepath).convert("L") # 转为灰度图
img = img.resize(img_size) # 改变图片尺寸
img_arr = np.array(img) / 255.0 # 归一化到0~1
images.append(img_arr)
labels.append(int(foldername))
images = np.array(images)
labels = np.array(labels)
return images, labels
data_path = "path/to/images"
img_size = (28, 28) # 图像尺寸
images, labels = read_images(data_path, img_size)
# 转为 [N, C, H, W] 形式
images = images.reshape(images.shape[0], 1, img_size[0], img_size[1])
# 返回数据集
dataset = {"images": images, "labels": labels}
```
c# 基于二维数组读取16位tiff格式的灰度图像的像素值
可以使用System.Drawing命名空间中的Bitmap类来读取16位Tiff格式的灰度图像像素值。下面是一个示例代码:
```csharp
using System.Drawing;
using System.Drawing.Imaging;
// ...
// 读取16位Tiff格式的灰度图像
Bitmap bitmap = new Bitmap("image.tif");
// 获取图像的宽度和高度
int width = bitmap.Width;
int height = bitmap.Height;
// 获取图像的像素格式
PixelFormat pixelFormat = bitmap.PixelFormat;
// 判断像素格式是否为16位灰度图像
if (pixelFormat != PixelFormat.Format16bppGrayScale)
{
throw new Exception("不是16位灰度图像");
}
// 锁定位图数据,获取像素值
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height),
ImageLockMode.ReadOnly, PixelFormat.Format16bppGrayScale);
// 获取像素值的字节数
int stride = bitmapData.Stride;
int bytesPerPixel = stride / width;
// 定义一个二维数组存储像素值
ushort[,] pixels = new ushort[height, width];
// 逐行读取像素值
unsafe
{
byte* p = (byte*)bitmapData.Scan0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// 获取当前像素的指针
ushort* pixelPtr = (ushort*)(p + y * stride + x * bytesPerPixel);
// 获取像素值
ushort pixelValue = *pixelPtr;
// 存储像素值
pixels[y, x] = pixelValue;
}
}
}
// 解锁位图数据
bitmap.UnlockBits(bitmapData);
```
上述代码使用LockBits方法锁定位图数据,获取像素值之后再使用UnlockBits方法解锁位图数据。在获取像素值时,使用了指针操作来提高效率。注意,由于C#中的多维数组是按行存储的,因此在存储像素值时,需要按照[y, x]的顺序存储。