RaviTej310
RaviTej310

Reputation: 1715

Copy and process images in python

I have written the following python code to traverse all the images in a folder(the folder contains only images). I want to obtain each image's negative and save it with a similar name. E.g. If original image is xyz.jpg, I want to save it's negative as xyz-n.jpg. How can I do this?

import os, sys

# Open a file
path = "required_path"
dirs = os.listdir( path )

# This would print all the files and directories
for file in dirs:
   print (file)

Upvotes: 0

Views: 319

Answers (3)

Abdul Fatir
Abdul Fatir

Reputation: 6357

You'll require PIL (Pillow). Also, use glob instead of os.listdir().

from PIL import Image
import PIL.ImageOps    
import glob

files = glob.glob('path/*.jpg') # Use *.* if you're sure all are images

for f in files:
  image = Image.open(f)
  inverted_image = PIL.ImageOps.invert(image)
  out = f[:f.rfind('.')]
  inverted_image.save('%s-n.png'%out)

Upvotes: 3

nucleon
nucleon

Reputation: 1158

I would recommend you to use an image processing library, e.g. scikit-image seems appropriate. The conversion code for a single file is as simple as:

from skimage.io import imread, imsave

image = imread('input.png')
negative = 255 - image
imsave('output.png', negative)

Wrapping this in a loop over all files in a directory should be easy.

Upvotes: 2

TheLazyScripter
TheLazyScripter

Reputation: 2665

I wrote this little program before you removed your last post to do exactly what you asked.

def make_negatives(dir, output_dir=False, file_types = ['jpg'], versioning=False):
    '''
        Create a series of negatives based on a directory
        :output_dir is the directory to output the negatives, if None, files will be placed in dir
        :file_types is a list of available file_types to create negatives from
        :dir is the desired directory to find images in
        :versioning is the desired string to be added to the end of the origonal name (_n, -n etc...)
        '''

    if output_dir:
        negatives_dir = os.path.abspath(output_dir)
    else:
        negatives_dir = os.path.abspath(dir)

    if not versioning or not isinstance(versioning, str):
        versioning = '_negatives'

    if not os.path.exists(negatives_dir):
        #create the negative directory if it dosen't already exist
        os.mkdir(negatives_dir)

    for i in os.listdir(dir):
        f_type = i.split('.')[-1] #find the file type jpg, png txt etc...
        if f_type in file_types:
            img = Image.open(os.path.abspath(os.path.join(dir, i))) #open the image
            inverted = Image.eval(img, lambda(x):255-x) #create a negative of the image
            new_image_name = i.split('.')[0]+'%s.%s'%(versioning, f_type) #determine the new image name
            inverted.save(os.path.abspath(os.path.join(negatives_dir, new_image_name))) #save image to the negatives directory

Upvotes: 1

Related Questions