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()
Related
I'm working on a program that reads csv file to get the names of colors, compares RGB values with RGB values of an image from URL. I think the program doesn't get image from URL since I tried to imshow() to check whether image is passed into program or not. I get this error
(-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'
This is the code:
import numpy as np #needed to work with matrix of an image
import pandas as pd #needed to work with color.csv
import cv2 #needed to work with image
import matplotlib.pyplot as pl #needed to work with plotting
import urllib.request#needed to work with image url
#step 1. Read csv file with name, RGB and HEX values.
#step 2. Set color detection function. Get value of pixels in a NumPy array
#step 3. Compare RGB value of a pixel with dataframe.
#step 4. Save the name and RBG value inside a file.
#image from url
def url_to_image(url): #doesn't get file, need to work upon this
resp = urllib.request.urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype='uint8')
image = cv2.imdecode(image,cv2.IMREAD_COLOR)
return image
#dataframe with 864 colors
index = ['color', 'color_name', 'hex','R','G','B']
csv = pd.read_csv('colors.csv', names = index, header = None)
def getColor(R,G,B):
minimum = 10000
for i in range(len(csv)):
distance = abs(R-int(csv.loc[i, 'R'])) + abs(G-int(csv.loc[i, 'G'])) + abs(B-int(csv.loc[i,'B']))
if(distance<=minimum):
minimum = distance
color_name = csv.loc[i, 'color_name']
return color_name
img = url_to_image("https://upload.wikimedia.org/wikipedia/commons/2/24/Solid_purple.svg")
cv2.imshow("image", img)
cv2.waitKey(0)
It doesn't work because you are trying to use an svg Image (which is vector based) to open in an Matrix like an JPEG or PNG image (which are raster based). It doesn't work like that with these.
Try loading a different Image like this
https://miro.medium.com/max/800/1*bNfxs62uJzISTfuPlOzOWQ.png EDIT sry wrong link
https://htmlcolorcodes.com/assets/images/colors/purple-color-solid-background-1920x1080.png
this will work because this is an png
As far as i know Opencv has no good support for SVG based Images
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
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)
There is a folder with 65 images. When i import(read in spyder) one by one(by first below code) images, the size of each image is (168, 192) which is according to data sheet. But when i import all these images together as a list with 65 members(by second below code) the size of each image(each member of list which it's name is image_list) changes to (192,168). Can anyone explain the reason of this change?
from PIL import Image
def read_img():
im = Image.open("E:\\Face Recognition Projet\\CroppedYale\\yaleB01\\yaleB01_P00A-060E-20.pgm")
im.show() # Show pictures
print(im.size) # Output image size
if __name__ == "__main__":
read_img() # Call read_img()
import numpy as np
from PIL import Image
import glob
image_list = []
for filename in glob.glob('E:\\Face Recognition Projet\\CroppedYale\\yaleB02\\*.pgm'): #assuming gif
im=Image.open(filename)
image_list.append(im)
The data sheet you have, whatever it is, may be listing sizes as height x width; PIL sizes are width x height.
I am programming a code that uses 30 images and I want to put those images in an array to resize them and then use them in other functions. I was trying some things but the second loop just shows me one unique image resized 30 times.
import cv2 as cv
import glob
import numpy as np
files = glob.glob ("C:/Users/Project/imgs/*.jpg")
images = np.empty(len(files))
#This loop reads images and show rgb images
#Works OK
for i in files:
#print(myFile)
images= cv.imread(i)
cv.imshow('myFile'+str(i),images)
new = []
for i in range(30):
new = cv.resize(images,(200,266))
cv.imshow('imagen', new)
cv.waitKey(0)
cv.destroyAllWindows()
If you want to keep many elements then first create empty list and next use apppend() to add element to list.
More or less
all_images = []
for name in files:
#print(name)
image = cv.imread(name)
cv.imshow('myFile '+name, image) # you don't need `str()`
all_images.append(image)
resized_images = []
for image in all_images:
new = cv.resize(image, (200,266))
cv.imshow('imagen', new)
resized_images.append(new)
If you want to resize only first 30 images
for image in all_images[:30]: