I have converted my image into a csv file and it's like a matrix but I want it to be a single row.
How can I convert all of the images in dataset into a csv file (each image into one line).
Here's the code I've used:
from PIL import Image
import numpy as np
import os, os.path, time
format='.jpg'
myDir = "Lotus1"
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
fileList = createFileList(myDir)
fileFormat='.jpg'
for fileFormat in fileList:
format = '.jpg'
# get original image parameters...
width, height = fileList.size
format = fileList.format
mode = fileList.mode
# Make image Greyscale
img_grey = fileList.convert('L')
# Save Greyscale values
value = np.asarray(fileList.getdata(),dtype=np.float64).reshape((fileList.size[1],fileList.size[0]))
np.savetxt("img_pixels.csv", value, delimiter=',')
input :
http://uupload.ir/files/pto0_lotus1_1.jpg
output:http://uupload.ir/files/huwh_output.png
From your question, I think you want to know about numpy.flatten(). You want to add
value = value.flatten()
right before your np.savetxt call. It will flatten the array to only one dimension and it should then print out as a single line.
The rest of your question is unclear bit it implies you have a directory full of jpeg images and you want a way to read through them all. So first, get a file list:
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
The surround your code with a for fileName in fileList:
Edited to add complete example
Note that I've used csv writer and changed your float64 to ints (which should be ok as pixel data is 0-255
from PIL import Image
import numpy as np
import sys
import os
import csv
#Useful function
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 myFileList:
print(file)
img_file = Image.open(file)
# img_file.show()
# 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')
#img_grey.save('result.png')
#img_grey.show()
# Save Greyscale values
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)
How about you convert your images to 2D numpy arrays and then write them as txt files with .csv extensions and , as delimiters?
Maybe you could use a code like following:
np.savetxt('np.csv', image, delimiter=',')
import numpy as np
import cv2
import os
IMG_DIR = '/home/kushal/Documents/opencv_tutorials/image_reading/dataset'
for img in os.listdir(IMG_DIR):
img_array = cv2.imread(os.path.join(IMG_DIR,img), cv2.IMREAD_GRAYSCALE)
img_array = (img_array.flatten())
img_array = img_array.reshape(-1, 1).T
print(img_array)
with open('output.csv', 'ab') as f:
np.savetxt(f, img_array, delimiter=",")
import os
import pandas as pd
path = 'path-to-the-folder'
os.chdir(path)
lists = os.listdir(path)
labels = []
file_lst = []
for folder in lists:
files = os.listdir(path +"/"+folder)
for file in files:
path_file = path + "/" + folder + "/" + file
file_lst.append(path_file)
labels.append(folder)
dictP_n = {"path": file_lst,
"label_name": labels,
"label": labels}
data = pd.DataFrame(dictP_n, index = None)
data = data.sample(frac=1)
data['label'] = data['label'].replace({"class1": 0, "class2": 1 })
data.to_csv("path-to-save-location//file_name.csv", index =None)
Related
I am trying to convert *.dcm file to *.jpg file.
while I do that
I am using this code :
import os
import numpy as np
import pydicom
from PIL import Image
def get_names_of_imgs_inside_folder(directory):
names = []
for root, dirnames, filenames in os.walk(directory):
for filename in filenames:
_, ext = os.path.splitext(filename)
if ext in [".dcm"]:
names.append(filename)
return names
def convert(directory):
im = pydicom.dcmread('Database/'+directory)
im = im.pixel_array.astype(float)
rescaled_image = (np.maximum(im,0)/im.max())*255 # float pixels
final_image = np.uint8(rescaled_image) # integers pixels
final_image = Image.fromarray(final_image)
return final_image
names = get_names_of_imgs_inside_folder('Database')
for name in names:
image = convert(name)
image.save(name+'.jpg')
but at line 20 I get this error :
File is missing DICOM File Meta Information header or the 'DICM'
prefix is missing from the header. Use force=True to force reading.
How can I fix this problem .Can anybody help me please
I am working on a robotics project in which a robot creates images in .pgm format (not camera images) continuously which I'm converting to .jpeg and saving to a directory. However, this directory keeps updating as more images keep getting added while I want to convert these images continuously in a video. I can already create a video from the images saved in one instance but what I want is to update the video continuously as a single file (streaming onto a URL) while images keep getting saved. Here is my code but it doesn't work in parallel for images as well as for videos. Anyone can help?
from PIL import Image
import os, glob
import cv2
import numpy as np
from os.path import isfile, join
# remove .yaml files
directory = "/home/user/catkin_ws/src/ros_map/map_pgms"
files_in_directory = os.listdir(directory)
filtered_files = [file for file in files_in_directory if file.endswith(".yaml")]
for file in filtered_files:
path_to_file = os.path.join(directory, file)
os.remove(path_to_file)
def batch_image(in_dir, out_dir):
if not os.path.exists(out_dir):
print(out_dir, 'is not existed.')
os.mkdir(out_dir)
if not os.path.exists(in_dir):
print(in_dir, 'is not existed.')
return -1
count = 0
for files in glob.glob(in_dir + '/*'):
filepath, filename = os.path.split(files)
out_file = filename[0:9] + '.jpg'
# print(filepath,',',filename, ',', out_file)
im = Image.open(files)
new_path = os.path.join(out_dir, out_file)
print(count, ',', new_path)
count = count + 1
im.save(os.path.join(out_dir, out_file))
if __name__ == '__main__':
batch_image('/home/user/catkin_ws/src/ros_map/map_pgms', './batch')
# convert the .jpgs to video
img_array = []
for filename in glob.glob('./batch/*.jpg'):
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width, height)
img_array.append(img)
out = cv2.VideoWriter('project.avi', cv2.VideoWriter_fourcc(*'DIVX'), 15, size)
for i in range(len(img_array)):
out.write(img_array[i])
out.release()
def load_img(img):
img = cv.imread(r"C:\Users\OneDrive\Desktop\Computer-Vision-with-Python\DATA\ **dynamic_img** ")
img = cv.cvtColor(img ,cv.COLOR_BRG2RGB)
return img
so this is the function.... what I want to do is call the function with any image from the destination folder and it should replace that dynamic_img with the name of the image
THANK YOU.
First you need to find all images in the directory:
import os
path = 'c:\\Users\\OneDrive\\and_so_on'
files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.jpg' in file:
files.append(os.path.join(r, file))
Then you can just iterate over files.
I'm in an introductory neural networking class so mind my ignorance. Also my first SO post.
I'm trying to resize some very highly resolved images within a dataset into 80x80p grayscale images in a new dataset. However, when I do this, I'd like to keep the filenames of each new image the same as the original image. The only way I know how to resave images into a new file is through a str(count) which isn't what I want. The filenames are important in creating a .csv file for my dataset later.
The only SO post I can find that is related is this:
Use original file name to save image
But the code suggested there didn't work - wasn't sure if I was going about it the wrong way.
import os
from PIL import Image
import imghdr
count=0
path1 = "/Users/..."
path2 = "/Users/..."
listing = os.listdir(path1)
for file in listing:
type = imghdr.what((path1 + file))
if type == "jpeg":
img = Image.open("/Users/..." +file).convert('LA')
img_resized = img.resize((80,80))
img_resized.save(path2 + str(count) + '.png')
count +=1
pass
pass
Reuse the original filename that you get from the for loop i.e. file
and, split it into filename and extension using os.path.splitext() like below:
import os
from PIL import Image
import imghdr
count=0
path1 = "/Users/..."
path2 = "/Users/..."
listing = os.listdir(path1)
for file in listing:
type = imghdr.what((path1 + file))
if type == "jpeg":
img = Image.open("/Users/..." +file).convert('LA')
img_resized = img.resize((80,80))
# splitting the original filename to remove extension
img_filename = os.path.splitext(file)[0]
img_resized.save(path2 + img_filename + '.png')
count +=1
pass
Another option, we can use python str's built-in split method to split the original filename by . and discard the extension.
import os
from PIL import Image
import imghdr
count=0
path1 = "/Users/..."
path2 = "/Users/..."
listing = os.listdir(path1)
for file in listing:
type = imghdr.what((path1 + file))
if type == "jpeg":
img = Image.open("/Users/..." +file).convert('LA')
img_resized = img.resize((80,80))
# splitting the original filename to remove extension
img_filename = file.split(".")[0]
img_resized.save(path2 + img_filename + '.png')
count +=1
pass
So, if an image has a name such as some_image.jpeg then, the img_filename will have a value some_image as we splitted by . and discarded .jpeg part of it.
NOTE: This option assumes the original_filename will not contain any . other than the extension.
I assume that image name is on path1. If so you can grap image name from there in this way:
x=path1.rsplit('/',1)[1]
We are splitting path1 on last slash and taking image name string via indexing.
i'm trying to retrieve images from my local directory using array list but i got all images from list but i don't know how to show images from list one by one.
Please help me if anyone knows.
my.py:
import os, os.path
imgs = []
# print(imgs)
path = "C:/Users/admin/PycharmProjects/my_module/static/files"
valid_images = [".jpg",".gif",".png",".tga"]
print(valid_images)
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
os.listdir(path).append(f)
# Image.show(f)
There are several options depending on your environment and visualization libraries. Check this good answer
You need to do from PIL import Image, then you could do Image.open(path + "/" + f).show(). Try this:
import os, os.path
from PIL import Image
imgs = []
path = "path/to/directory"
valid_images = [".jpg", ".gif", ".png", ".tga"]
print(valid_images)
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
if ext in valid_images:
imgs.append(path + "/" + f)
img = Image.open(path + "/" + f)
img.show()
print(imgs)
I have tried and i got my expected output.
py:
import os
from PIL import Image
img=[]
path="C:/Users/admin/PycharmProjects/my_module/static/files/"
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
os.listdir(path).append(f)
image = Image.open(f)
image.show()