Python OpenCV- Problems reading files on Windows - python

I need to read a folder with a lot of .bmp files, and put all of the images on a lits of images. I do not know how to handle the adress. I was doing some thing like this:
adress = "c:/Users/My Name/Desktop/assignment/*.bmp"
imageArray = [cv2.imread(file) for file in glob.glob(adress)]
numImg = len(imageArray)
Inside the assignment folder, there is the Images folder with all the images I need. How to make this work?

Change working directory first:
If you change to the directory of interest first, it may be easier.
import glob, os
os.chdir("/mydir")
image_type = "*.bmp"
imageArray = [cv2.imread(file) for file in glob.glob(image_type)]
numImg = len(imageArray)
This LINK has some nice info about reading files in directories

Related

How to loop over a folder, and recreate them in another folder with same structure?

I want to process a folder and blur the images and recreate them in another folder while preserving the structure.
My source folder has the following structure
Data/
test1/
test2/
6.png
4.png
5.jpeg
1.jpg/
2.jpg
3.jpeg
I wanted to blur all these images and save them in another folder
src = 'C:\Users\shakhansho\Downloads\Data' #folder with images
dst = 'C:\Users\shakhansho\Downloads\Output' #folder for output
let's say I have a function which takes a path to image and then applies blurring and then saves it in the same directory blur(path_to_img)
How can I loop over the src files, blur and then save in dst folder with preserving the structure.I would like the dst folder contain the same folder name and image names but blurred.
I would advise using glob.glob (or glob.iglob) for this. It can recursively find all files under a directory. Then, we can simply open the images in some way, transform them, find the output file and folder, optionally create that folder, and write out transformed images. The code contains comments to elaborate these steps slightly.
import glob
import os
# Recursively find all files under Data/
for filepath in glob.iglob("Data/**/*.*", recursive=True):
# Ignore non images
if not filepath.endswith((".png", ".jpg", ".jpeg")):
continue
# Open your image and perform your transformation
# to get the blurred image
with open(filepath, "r") as f:
image = f.read()
blurred = transform(image)
# Get the output file and folder path
output_filepath = filepath.replace("Data", "Output")
output_dir = os.path.dirname(output_filepath)
# Ensure the folder exists
os.makedirs(output_dir, exist_ok=True)
# Write your blurred output files
with open(output_filepath, "w") as f:
f.write(blurred)
I recreated your file structure, and my program was able to re-create the exact file structure, but under Output instead.

How to write and transform image files from one directory to another directory using open cv?

I am attempting to copy and apply a horizontal transformation to all images from one of my directories (directory_a), and then write them to another (directory_b) using cv2. All images are in png format. This is my first time using open cv/cv2.
When I use the code I currently have (see below), the transformation is applied but the images are saved to the same directory. Does anyone know how to properly do this?
from glob import glob
import cv2
#Flip Image horizontally and add Image to directory_b Folder
directory_a = '/content/drive/MyDrive/no_copies2/train/directory_a_images'
directory_b = '/content/drive/MyDrive/no_copies2/train/directory_b_images'
input_files = glob(os.path.join(directory_a, "*.png"))
for file in input_files:
img = cv2.imread(file)
horizontal_img = cv2.flip(img, 1)
cv2.imwrite(os.path.join(directory_b, file + '_flip_v' + '.png'), horizontal_img)
file variable is holding the path to the whole path, try:
cv2.imwrite(os.path.join(directory_b, os.path.basename(file).split(".")[0] + '_flip_v' + '.png'),
horizontal_img)
It might have to do with Google Colab. Make sure you have all directories created before running the code. I previously tried doing something similar and not setting up the directories properly in the drive came with some issues.

Copying/pasting specific files in batch from one folder to another

I'am really new to this python scripting thing, but pretty sure, that there is the way to copy files from one folder (via given path in .txt file) to another.
there would be directly path to the folder, which contains photo files
I'am working with huge amounts of photos, which contains gps metadata (so i need not to lose it).
Really apreciate any help, thanks.
Here is a short and simple solution:
import shutil
import os
# replace file_list.txt with your files
file_list = open("file_list.txt", "r")
# replace my_dir with your copy dir
copy_dir = "my_dir"
for f in file_list.read().splitlines():
print(f"copying file: {f}")
shutil.copyfile(f, f"{copy_dir}/{os.path.split(f)[1]}")
file_list.close()
print("done")
It loops over all the files in the file list, and copies them. It should be fast enough.

How can I make directory & put image in the directory?

How can I make directory & put image in the directory?
I wrote the following code in data.py:
import os
import cv2
import argparse
import numpy as np
import math
parser = argparse.ArgumentParser(description='')
parser.add_argument('input_dir' ,help='input directory')
parser.add_argument('output_dir' ,help='out directory')
args = parser.parse_args()
def find_all_files(directory):
for root, dirs, files in os.walk(directory):
for file in files:
p=os.path.join(root, file)
p=p.split("/")[len(p.split("/"))-2]
name, ext = os.path.splitext(p)
yield os.path.join(root, file)
dirname=args.output_dir
if not os.path.exists(dirname):
os.mkdir(dirname)
folder_img = find_all_files(args.input_dir)
im =cv2.imread(folder_img)
cv2.imwrite(args.output_dir ,im)
Now when I run command python data.py ./photo ./copy_photo, find a writer for the specified extension in function imwrite error happens. I want to make a directory copy_photo and put images made by this code in the directory. The copy_photo folder is made, so what is wrong in my code? How should I fix this? Am I wrong to write the way of putting images in the copy_photo folder?
find_all_files is a generator. The variable folder_img will be bound to that generator. Calling cv2.imread() on that generator is not going to work because imread() expects an image file, not a generator.
You need to iterate over the generator to copy each file one by one. Something like this:
folder_img = find_all_files(args.input_dir)
for filename in find_all_files(args.input_dir):
im = cv2.imread(filename)
cv2.imwrite(os.path.join(args.output_dir, os.path.basename(filename)), im)
Note also that args.output_dir is a string that represents the desination directory name. You need to specify the path of the file including the directory. Use os.path.join() and os.path.basename() to do that.
If all you are wanting to do is to copy the files from one directory to another then you should perhaps use shutil.copytree as there is no point in opening the image files and then writing them back out. Also, your find_all_files() generator function will pass back all files, including directories, so you need to add some logic to detect image files and filter out those that are unwanted.
cv2.imread() accepts a single file name, but you are calling it with a (generator returning a) list of files.
Try this:
def find_all_files(directory):
for root, dirs, files in os.walk(directory):
for file in files:
# Comment out dead code
'''
p=os.path.join(root, file)
p=p.split("/")[len(p.split("/"))-2]
name, ext = os.path.splitext(p)
'''
# Changed this to return a tuple
yield root, file
for dirname, imagefile in find_all_files(args.input_dir):
im =cv2.imread(os.path.join(dirname, imagefile))
cv2.imwrite(os.path.join(args.output_dir, imagefile), im)
Because imwrite() needs to receive a filename parameter, I changed find_all_files to return a tuple, so you can use the same filename for the output, and choose which directory name you add in front.
Rewriting the images seems like a very inefficient way to do this, though. Why don't you simply copy the files?

Reading images in python using OpenCV and OS libraries

I have a folder with numerous images(about 300), I am gonna save the python file which will be splitting the images into red, green and blue channels and saving them as _red, _green, _blue, preceded by the original image name itself in a different folder. For example if the image is named "image 001", then the images obtained after the split are: "image 001_red", "image 001_green", "image 001_blue". Now, is there a way I can obtain the images one after the other using the OS library? (Appreciate any answer what-so-ever, because this is my first question on this site)
You are asking how to read an image list from a directory to python. Here is how.
from os import walk
# Get file list
def getImageList(path):
for (dirpath, dirnames, filenames) in walk(path):
return filenames
# Demo printing file names
filelist = getImageList("path/to/image/dir")
for fileName in fileList:
print(fileName)
getImageList(path) function returns all files (not directories) in a given path. Place all your images inside a directory, and use the function to get the file list.
Hope this helped.

Categories

Resources