Sorry if the question's been asked before, I couldn't find a solution that I either implemented correctly or that helped achieve my desired results.
Summary: The script should look inside a folder, import images using opencv, apply a filter to the images, and finally save the pre-processed image to the specified path. The names should ideally contain the original filename plus "preproc" added, or anything indicating having been filtered.
What works: I managed to read all images, import them, and apply the filter.
Save images in loop with different names
This helped some.
Save multiple images with OpenCV and Python
This worked before but I don't think I had implemented it into the script that read all images.
from __future__ import (division, absolute_import, print_function, unicode_literals)
import glob
import os,sys
import cv2 as cv
import numpy as np
from pandas import DataFrame as df
import pandas as pd
from matplotlib import pyplot as plt
########
#Globals
#########
img_dir = "path_to_images/*.*"
###########
#Functions
###########
def white_balance(img):
result = cv.cvtColor(img, cv.COLOR_BGR2LAB)
avg_a = np.average(result[:, :, 1])
avg_b = np.average(result[:, :, 2])
result[:, :, 1] = result[:, :, 1] - ((avg_a - 128) * (result[:, :, 0] / 255.0) * 1.1)
result[:, :, 2] = result[:, :, 2] - ((avg_b - 128) * (result[:, :, 0] / 255.0) * 1.1)
result = cv.cvtColor(result, cv.COLOR_LAB2BGR)
return result
## Get all the images in the specified dir:
images = sorted(glob.glob(img_dir))
#Reading images in folder
for image in images:
img = cv.imread(os.path.join(img_dir, image)) #Read images one by one
################
#Pre-processing#
################
#Performing white balancing (gray world)
#final = np.hstack((img, white_balance(img))) #white balancing; showing Original and filtered.
final = white_balance(img) #white balance on a single image.
#Saving images:
i = 0
cv.imwrite("path_to_results/preproc%04i.jpg" %i, final) #save images in sequence (numbering)
i += 1 #numbering variable
What doesn't work: Images are saved but somewhere I haven't specified correctly an index to save the images in a sequence (i.e. result_1, result_2,...). The script overwrites the last image only.