Th h5 file does not have a group or subgroup, and when I try to extract images it shows me this error. These are depth images.
This code works for h5 file with group i.e. images then I just write image_ds = hf['images'] and it works, but for h5 file without group doesn't work.
Maybe some error in imwrite function, because when I print(IMAGE_arr) and print(imagename) it prints fine. The number of dimensions are 3 and type is float32
Here is my code:
import h5py
import numpy as np
import cv2
save_dir = 'C:/Users.../depth_imgs'
with h5py.File('depth.h5', 'r') as hf:
image_ds = hf
for imagename in image_ds.keys():
IMAGE_arr = image_ds[imagename][()]
cv2.imwrite(f"{save_dir}/{imagename}", IMAGE_arr)
cv2.waitKey(1000)
cv2.destroyAllWindows()
Loaded data:
enter image description here
enter image description here
Related
I am trying to convert this .tif file to a .png, here is the image (I attached a link because it is 250mb): https://drive.google.com/file/d/1nEvG8O5NM1bsKM-fSo66QJF7mZyR_fh-/view?usp=sharing
Here is my current code, it returns an grayscale image with multiple copies of the original .tif in one .png, it is suppose to return an RGB image:
import rasterio
import numpy as np
from PIL import Image
dataset = rasterio.open("world.tif")
window = rasterio.windows.Window(0, 0, 21600, 10800)
out = dataset.read(window=window)
out = out.reshape(10800, 21600, 3).astype(np.uint8)
img = Image.fromarray(out, "RGB")
img.save("out.png")
I'm not sure why you are mixing up PIL/Pillow and raster like that. You can just do the following with PIL:
from PIL import Image
# Allow monster large images
Image.MAX_IMAGE_PIXELS = None
# Load image
im = Image.open('world.tif')
# Reduce to manageable size and save as PNG
small = im.resize((2160,1080))
small.save('result.png')
I have images that are saved into h5 file, so now I'm wondering is it possible to extract images from h5 file in a folder? I wrote this code but it doesn't work. It save an image in folder but can't open. You can see that on the picture.
dset.h5 contains of 5 images and I need to save that images. For now I'm trying to save just one (hiking_125.jpg).
`
import h5py
import numpy as np
import cv2
save_dir = 'C:/Users.../depth'
with h5py.File('dset.h5', 'r') as hf:
IMAGE = hf['image']
print(IMAGE['hiking_125.jpg'])
print(IMAGE['hiking_125.jpg'].dtype)
#IMAGE = np.array(IMAGE)
item = []
item = np.array(IMAGE['hiking_125.jpg']).reshape(-1, 500, 600, 3)
cv2.imwrite(f"{save_dir}/.jpg", item)
cv2.imshow('Color image', item)
print(item)
`
You have a number of small errors in the code above.
This code snippet should work. It assumes dataset hf['image']['hiking_125.jpg'] is NumPy array for the image and does not need to be reshaped). Note code added to address issues displaying the image with cv.imshow().
save_dir = 'C:/Users.../depth'
with h5py.File('dset.h5', 'r') as hf:
imagename = 'hiking_125.jpg'
# get an array from the imagename dataset:
IMAGE_arr = hf['image'][imagename][()]
# create image from array
cv2.imwrite(f"{save_dir}/{imagename}", IMAGE_arr)
# post image to a window
cv2.imshow(f'Image: {imagename}', IMAGE_arr)
# keep window posted for 2500 msec
cv2.waitKey(2500)
# destroy CV2 window when done
cv2.destroyAllWindows()
You can extend the code above to export all images from dataset hf['image'] with the following. It's a small modification that uses a loop to create each file by getting the dataset names using the .keys() method.
with h5py.File('dset.h5', 'r') as hf:
image_ds = hf['image']
for imagename in image_ds.keys():
# get an array from the imagename dataset:
IMAGE_arr = image_ds[imagename][()]
# create image from array
cv2.imwrite(f"{save_dir}/{imagename}", IMAGE_arr)
# post image to a window
cv2.imshow(f'Image: {imagename}', IMAGE_arr)
# keep window posted for 2500 msec
cv2.waitKey(2500)
# destroy CV2 window when done
cv2.destroyAllWindows()
I created an model in blender. From here I took 2d slices through the y-plane of that model leading to the following.
600 png files each corresponding to a ylocation i.e y=0, y=0.1 etc
Each png file has a resolution of 500 x 600.
I am now trying to merge the 600 pngs into a h5 file using python before loading the .h5 into some software. I find that each individual png file is read fine and looks great. However when I look at the final 3d image there is some stretching of the image, and im not sure how this is being created.
The images are resized (from 600x600 to 500x600, but I have checked and this is not the cause of the stretching). I would like to know why I am introducing such stretching in other planes (not y-plane).
Here is my code, please note that there is some work in progress here, hence why I append the dataset to a list (this is to be used for later code)
from PIL import Image
import sys
import os
import h5py
import numpy as np
import cv2
from datetime import datetime
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(dir_path + '//..//..')
Xlen=500
Ylen=600
Zlen=600
directory=dir_path+"/LowPolyA21/"
for filename in os.listdir(directory):
if fnmatch.fnmatch(filename, '*.png'):
image = Image.open(directory+filename)
new_image = image.resize((Zlen, Xlen))
new_image.save(directory+filename)
dataset = np.zeros((Xlen, Zlen, Ylen), np.float)
# traverse all the pictures under the specified address
cnt_num = 0
img_list = sorted(os.listdir(directory))
os.chdir(directory)
for img in (img_list):
if img.endswith(".png"):
gray_img = cv2.imread(img, 0)
dataset[:, :, cnt_num] = gray_img
cnt_num += 1
dataset[dataset == 0] = -1
dataset=dataset.swapaxes(1,2)
datasetlist=[]
datasetlist.append(dataset)
dz_dy_dz = (float(0.001),float(0.001),float(0.001))
for j in range(Xlen):
for k in range(Ylen):
for l in range(Zlen):
if datasetlist[i][j,k,l]>1:
datasetlist[i][j,k,l]=1
now = datetime.now()
timestamp = now.strftime("%d%m%Y_%H%M%S%f")
out_h5_path='voxelA_'+timestamp+'_flipped'
out_h5_path2='voxelA_'+timestamp+'_flipped.h5'
with h5py.File(out_h5_path2, 'w') as f:
f.attrs['dx_dy_dz'] = dz_dy_dz
f['data'] = datasetlist[i] # Write data to the file's primary key data below
Example of image without stretching (in y-plane)
Example of image with stretching (in x-plane)
Currently, I am working on training the images for facial recognition system. I am using Python, OpenCV for doing so. I have collected the samples from the webcam, however, the size of sample images differs. The example for the size of sample images is 376 x 376, 412 x 412, 836 x 836.
The screenshot of current working directory:
The sample images are saved within the main folder named 'sampleImgFolder' and under the main folder specific folder for each sample.
Source code for training image
import os
import cv2
import numpy as np
from PIL import Image
recognizer = cv2.face.LBPHFaceRecognizer_create()
targetImagesDirectory="sampleImgFolder/"
dataset = cv2.CascadeClassifier('resources/haarcascade_frontalface_default.xml')
def getImageWithID(path):
#empty list to store processed data
sampleFaces = []
sampleFaceId = []
os.chdir(targetImagesDirectory)
for directory in os.listdir():
os.chdir(directory)
for files in os.listdir():
imagePath = '{}/{}'.format(os.getcwd(), files)
imagePil = Image.open(imagePath).convert('L')
imageNumpy = np.array(imagePil, 'uint8') #conversion of normal image to numpy array
#imageNumpy.astype(np.float32)
#detect face
faces = dataset.detectMultiScale(imageNumpy)
#extracting id from file name
id = files.split('_')
id = id[0].split('-')
id = id[2]
for (x, y, w, h) in faces:
sampleFaces.append(imageNumpy[y:y + h, x:x + w])
sampleFaceId.append(id)
os.chdir('../')
os.chdir('../')
return np.array(sampleFaceId), sampleFaces
print("reading images")
Ids,faces=getImageWithID(targetImagesDirectory)
print('reading completed')
recognizer.train(faces,Ids)
print("training")
#train the dataset. Create a file name trainningData.yml
recognizer.write('train/trainningData.yml')
cv2.destroyAllWindows()
I am getting following error while running above code:
That is because the datatype of Ids is a list[str]. .train() methods accepts int for labels
I'm working on a The Japanese Female Facial Expression (JAFFE) Database. You can find the database on this link http://www.kasrl.org/jaffe.html.
When I download the database I got a list of pictures. I would like to convert these image files into a CSV file but I'm still new in deep learning and I don't know how. Someone proposed that I work with OpenCV. what should I do?
i have simple example
i hope this help you.
from PIL import Image
import numpy as np
import sys
import os
import csv
def createFileList(myDir, format='.jpg'):
fileList = []
print(myDir)
for root, dirs, files in os.walk(myDir, topdown=False):
for name in files:
if name.endswith(format):
fullName = os.path.join(root, name)
fileList.append(fullName)
return fileList
# load the original image
myFileList = createFileList('path/to/directory/')
for file in fileList:
print(file)
img_file = Image.open(file)
# get original image parameters...
width, height = img_file.size
format = img_file.format
mode = img_file.mode
# Make image Greyscale
img_grey = img_file.convert('L')
value = np.asarray(img_grey.getdata(), dtype=np.int).reshape((img_grey.size[1], img_grey.size[0]))
value = value.flatten()
print(value)
with open("img_pixels.csv", 'a') as f:
writer = csv.writer(f)
writer.writerow(value)
Install pillow, numpy, pandas
Convert the image to RGB
plot RGB along with x,y co-ordinates in a pandas Dataframe
Save the dataframe as csv
Sample working code as below
from PIL import Image
from numpy import array, moveaxis, indices, dstack
from pandas import DataFrame
image = Image.open("data.tiff")
pixels = image.convert("RGB")
rgbArray = array(pixels.getdata()).reshape(image.size + (3,))
indicesArray = moveaxis(indices(image.size), 0, 2)
allArray = dstack((indicesArray, rgbArray)).reshape((-1, 5))
df = DataFrame(allArray, columns=["y", "x", "red","green","blue"])
print(df.head())
df.to_csv("data.csv",index=False)
You don't need to write any code, you can just use vips on the command-line on macOS, Linux or Windows.
So, in Terminal (or Command Prompt, if on Windows):
vips im_vips2csv TM.AN1.190.tiff result.csv
will convert the 256x256 greyscale image TM.AN1.190.tiff into a 256 line CSV with 256 entries per line. Simples!
If you want to replace the tab separators by commas, you can do:
tr '\t' , < result.csv > NewFile.csv