Converting directory with images to csv file in python - python

Im trying to copy the pixel information of a group of images to a CSV, however when I try the following code, Im unable to create the csv. Is there any other way to copy the pixels to a csv?
from PIL import Image
import numpy as np
import sys
import os
import csv
# default format can be changed as needed
def createFileList(myDir, format='.png'):
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('/test/surprise')
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("imagenes.csv", 'a') as f:
writer = csv.writer(f)
writer.writerow(value)
I would like to generate a csv with the pixel information similar to FER2013.csv as can be see in the following image.

Related

how to process all images on a folder with python

I have a python script to procces jpeg on a folder and overwrite the names after done
from PIL import Image, ImageOps, JpegImagePlugin, ImageEnhance
#import jpegs from Repaired folder
im = Image.open('photo_2022-06-09_19-58-19.JPG')
# Crop
im = ImageOps.crop(im, border=17)
# Constract
im = ImageOps.autocontrast(im, cutoff = 1)
#sharpness
enhancer = ImageEnhance.Sharpness(im).enhance(3)
im = ImageOps.posterize(im, bits=8)
#color
enhancer = ImageEnhance.Color(im).enhance(3)
#save all jpegs and overwrite original file names
im.save("photo_2022-06-09_19-58-19.JPG", quality="maximum")
How can i process all jpeg files in that dir have a folder "repaired" and Overwrite the name of each processed file with the original file name?
I would use glob and do something like this:
import glob
from PIL import Image, ImageOps, JpegImagePlugin, ImageEnhance
for fname in glob.glob('./repaired/*.JPG'):
im = Image.open(fname)
im = ImageOps.crop(im, border=17)
im = ImageOps.autocontrast(im, cutoff = 1)
enhancer = ImageEnhance.Sharpness(im).enhance(3)
im = ImageOps.posterize(im, bits=8)
enhancer = ImageEnhance.Color(im).enhance(3)
im.save(fname, quality="maximum")
You can print fname to see what it looks like, and process that string if you need to get the filename out, e.g. to write the file into a different folder.
So it should be like this
import os
from PIL import Image, ImageOps, JpegImagePlugin, ImageEnhance
#import jpegs from Repaired folder
for filename in os.listdir():
if filename.endswith(".jpg"):
im = Image.open(filename)
# Crop
im = ImageOps.crop(im, border=17)
# Constract
im = ImageOps.autocontrast(im, cutoff = 1)
#sharpness
enhancer = ImageEnhance.Sharpness(im).enhance(3)
im = ImageOps.posterize(im, bits=8)
#color
enhancer = ImageEnhance.Color(im).enhance(3)
#save all jpegs and overwrite original file names
im.save(filename, quality="maximum")
else:
continue

How to convert latex to image in python

In a part of my project for creating a dataset, I have a text file containing a list of a bunch of latex equations . Now I want to convert them into images through python in diffrent font sizes. But i dont know how to do it. Please help.
This is the list of latex symbols I am using:- https://docs.mathpix.com/#vocabulary
#
import shutil
import os
from pdflatex import PDFLaTeX
from pdf2image import convert_from_path
from PIL import Image
def crop(file):
img = Image.open(file)
area = (300,300, 800, 800)
cropped_img = img.crop(area)
cropped_img.save(file)
def save_images(images_names,pdf_path,images_path=""):
# Store Pdf with convert_from_path function
images = convert_from_path(pdf_path)
if len(images_names)==0:
print("names is empty")
return
i=0
for img in images:
img.save(images_path+"/"+images_names[i]+".jpg", 'JPEG')
crop(images_path+"/"+images_names[i]+".jpg")
i+=1
print("Successfully converted")
def create_image_from_latex(image_name,latex):
if "rough" not in os.listdir():
os.mkdir("rough")
if "images_from_latex" not in os.listdir():
os.mkdir("images_from_latex")
f=open("rough/a.tex","w+")
f.write("\\documentclass{article}\n\\usepackage{chemfig}\n\\begin{document}\n")
f.write(latex+"\n")
f.write(r"\end{document}")
f.close()
#print(os.getcwd()+"/a.tex")
#tex="/a.tex"
pdfl = PDFLaTeX.from_texfile('rough/a.tex')
pdf, log, completed_process = pdfl.create_pdf(keep_pdf_file=True, keep_log_file=False)
f=open("rough/a.pdf","wb")
f.write(pdf)
f.close()
save_images([image_name],"a.pdf","images_from_latex")
os.remove("rough/a.pdf")
shutil.rmtree("rough")
#create_image_from_latex("new_image",lat)
def create_images_from_text_file_with_latexes(text_file):
with open(text_file) as f:
latexes=f.readlines()
ind=1
for lat in latexes:
create_image_from_latex("%0.3d_"%ind,lat)
ind+=1
#

Display FileName of a Image Python imshow

Please,
I'm trying to display the filename of a jpeg but i could not find how to.
I want to display the image + the filename of the image.
img_dir = "paintings/"
data_path = os.path.join(img_dir,'*g')
files = glob.glob(data_path)
data = []
for f1 in files:
img = imageio.imread(f1)
data.append(img)
plt.imshow(data[40])
Thanks
You can try plt.title(filename):

Cropping snippets from a image on the basis of coordinates from csv file

I have image which comprises of several cells (like any general form). I was provided with coordinates in csv file which have roi of part of image which i need to crop and save it as a new file with the image file name as folder name and the coordinate cell name as image name in the image folder.
I was able to crop image individually using crop from pil library but i am not sure how to extract coordinate data of several cells from image and on the basis of that crop roi from image.
import glob,os,sys
from PIL import Image
class ROIExtraction:
def readImages(inputFolder):
ext = ['.png', '.jpg', '.gif', '.jpeg', '.tif', '.tiff']
files = []
path = inputFolder + "/*.*"
files = glob.glob(path)
imageFiles=[]
for i in files:
exten=os.path.splitext(i)[1]
if exten in ext:
imageFiles.append(i)
return imageFiles
def processRoi(imageFiles):
for imagePath in imageFiles:
img_name = os.path.splitext(os.path.basename(imagePath))[0]
output_folder = sys.argv[2]+'/'+img_name+'/'
os.makedirs(output_folder, exist_ok=True)
# import image
image = Image.open(imagePath)
img2 = image.crop((1385,45,2256,149))
img2.show()
img2.save(output_folder+'{}.png')
imageFiles = ROIExtraction.readImages(sys.argv[1])
ROIExtraction.processRoi(imageFiles)
In the above code I had put coordinates manually but i want to write a program where the coordinates are extracted from csv file and on the basis of that cropping of roi from image is done.
here is the example of csv file content-
SERIAL_NO|N|1385,45,871,104|1|?
CUST_ID|N|1704,211,552,71|1|?
PROD_TYPE|A|367,286,1167,74|1|?
BRANCH_CODE|N|1892,429,254,74|1|?
CONSTITUION|C|279,1355,85,62-539,1355,75,59-757,1352,72,62-884,1352,52,55-998,1352,68,55-1310,1352,68,49-1596,1349,65,55-1762,1352,68,49-1905,1352,69,52-2113,1352,62,49-78,1423,61,49-282,1410,78,65-432,1417,68,58-656,1417,78,55-969,1414,71,61-1222,1414,72,55-1391,1414,78,55|1|Sole proprietor?Partnership?LLP?HUF?Private Ltd Company?Public Ltd Company?Society?Trust?NGO/NPO?SHG?Association?Club?University?Government Body?Financial Inst?Bank?JLG?
ACTIVITY|C|221,1498,71,52-400,1498,71,52-552,1495,59,45-702,1498,65,49-881,1495,62,49-1043,1495,69,52-1252,1495,58,42-1473,1495,75,49-1671,1495,65,52-1935,1485,74,59-224,1563,65,49-734,1553,59,52-1056,1557,62,45|1|Agri?Mfg?Trade?Finance?Bank?Transport?Services?Govt?Real Estate?Stock Broker?Jewels/Gems/Precious Metal dealer?Money Services?Others (specify)?
NAME_AUTH_SIG1|A|97,1713,1327,65|1|?
path ="csv.csv"
file = open(path)
for line in file.readlines():
tmp = line.split("|")
name = tmp[0]
cord = tmp[3]
all_snp_cord = cord.split("-")
for snp_cord in all_snp_cord:
snippet = snp_cord.split(",")
#do somthing with cordinats

How do I fix my error with PIL and numpy images

You have to run it in the folder with a couple images and run shuffle_all_images() and it will create new folder and randomly generate all of the values for each pixel. I think it has to do with not converting to numpy images as opposed to PIL images?, but I can't figure it out.
import random
import os.path
import PIL
import numpy
def image_shuffle(original_image):
for row in len(original_image):
for col in len(original_image[1]):
r,g,b = original_image[row][col]
r = random.randint(1,255)
g = random.randint(1,255)
b = random.randint(1,255)
original_image[row][col] = [r, g, b]
return original_image
def get_images(directory=None):
""" Returns PIL.Image objects for all the images in directory.
If directory is not specified, uses current directory.
Returns a 2-tuple containing
a list with a PIL.Image object for each image file in root_directory, and
a list with a string filename for each image file in root_directory
"""
if directory == None:
directory = os.getcwd() # Use working directory if unspecified
image_list = [] # Initialize aggregaotrs
file_list = []
directory_list = os.listdir(directory) # Get list of files
for entry in directory_list:
absolute_filename = os.path.join(directory, entry)
try:
image = PIL.Image.open(absolute_filename)
file_list += [entry]
image_list += [image]
except IOError:
pass # do nothing with errors tying to open non-images
return image_list, file_list
def shuffle_all_images(directory=None):
""" Saves a modfied version of each image in directory.
Uses current directory if no directory is specified.
Places images in subdirectory 'modified', creating it if it does not exist.
New image files are of type PNG and have transparent rounded corners.
"""
if directory == None:
directory = os.getcwd() # Use working directory if unspecified
# Create a new directory 'modified'
new_directory = os.path.join(directory, 'modified')
try:
os.mkdir(new_directory)
except OSError:
pass # if the directory already exists, proceed
#load all the images
image_list, file_list = get_images(directory)
#go through the images and save modified versions
for n in range(len(image_list)):
# Parse the filename
filename, filetype = file_list[n].split('.')
# Round the corners with radius = 30% of short side
new_image = image_shuffle(image_list[n])
#save the altered image, suing PNG to retain transparency
new_image_filename = os.path.join(new_directory, filename + '.png')
new_image.save(new_image_filename)
The image_shuffle function is wrong.
It should be:
for row in range(original_image.size[0]):
for col in range(original_image.size[1]):
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
original_image.putpixel((row, col), (r,g,b))
You want to have color values starting from 0 unless you don't want to get all the possible colors.

Categories

Resources