Python/Opencv save multiple images to folder with different names - python

I am working on image processing, I have a folder with all of the images that needs to be processed, and I want to save all the processed images to another folder. How do I do that?
for img in glob.glob("Img/*.png"):
path = '/result'
image = cv2.imread(img)
angle, rotated = correct_skew(image)
print(angle)
cv2.imwrite(os.path.join(path , 'img.png'), rotated)
cv2.waitKey(1)
This code can read the image and process it, but I can't figure out how to save all the images with different names, like I want it to be img1.png, img2.png, etc.
Or is there anyway that I can save the images to another folder with the same names as before?

In order to save your processed images in a serial manner, you can use enumerate. When a loop is initiated using enumerate, a counter is also initiated. And each iteration yields an integer number.
In the following case i is the integer value which increments for each iteration. i is used as part of the file name to save the processed image
path = '/result'
for i, img in enumerate(glob.glob("Img/*.png"), 1):
image = cv2.imread(img)
angle, rotated = correct_skew(image)
print(angle)
cv2.imwrite(os.path.join(output_path, 'img_{}.png'.format(i)), rotated)

Save the last line as a variable wrapped in a string()
Then cv2.imwrite(variable)for the last line.
#My thought is to change the type to a string and then write the file as originally desired. When you save as a string you can change whatever type it is turning into inside the for statement.

Related

How do I generate a small image randomly in different parts of the big image?

Let's assume there are two images. One is called small image and another one is called big image. I want to randomly generate the small image inside the different parts of the big image one at a time everytime I run.
So, currently I have this image. Let's call it big image
I also have smaller image:
def mask_generation(blob_index,image_index):
experimental_image = markup_images[image_index]
h, w = cropped_images[blob_index].shape[:2]
x = np.random.randint(experimental_image.shape[0] - w)
y = np.random.randint(experimental_image.shape[1] - h)
experimental_image[y:y+h, x:x+w] = cropped_images[blob_index]
return experimental_image
I have created above function to generate the small image in big image everytime I call this function. Note: blob index is the index that I use to call specific 'small image' since I have a collection of those small images and image_index is the index to call specific 'big images'. Big images are stored in the list called experimental_image and small images are stored in list called markup images
However, when I run this, I do get the small image randomly generated but the previously randomly generated image never gets deleted and I am not too sure how to proceed with it,
Example: When I run it once
When I run it twice
How do I fix this? Any help will be appreciated. Thank you
I tried the above code but didn't work as I wanted it to work
I suppose you only want the small random image you generated in this iteration in your code.
The problem you have, is due to the modification of your calling args.
When you call your function multiple times with the same big image
markup_image = ...
result_1 = mask_generation(blob_index=0, image_index=0)
result_2 = mask_generation(blob_index=1, image_index=0)
You get in result_2 both small images.
This is due to the writing to the original image in
experimental_image[y:y+h, x:x+w] = cropped_images[blob_index]
This adds the small image to your original image in your list of images.
When getting this image the next time, the small image is already there.
To fix:
Do not alter your images, e.g. by first copying the image and then adding the small image in your function
Probably even better: Only give your function a big and small image, and make sure that they always receive a copy

Applying filter to every photo in directory

I am new to python, so go easy on me! I am trying to apply a blur to every .bmp image in a folder. I am able to get the first half of the code to work, so the filter is applied to all the photos, but then I can't get it to re-save each image. I want to keep the original images, and add the new images to the folder. Here's what I have:
from PIL import Image from PIL import ImageFilter import os, fileinput, sys
##for every item in X folder that ends in X, apply a basic blur to the image##
for entry in os.scandir('/Users/kh'):
if entry.path.endswith('.bmp'):
img = Image.open(entry.path)
img = img.filter(ImageFilter.BoxBlur(2))
img.show()
##and then re-save each of those new images under a new filename##
# Split our original filename into name and extension
(name, extension) = os.path.splitext(filepath)
# Save with "_blur" added to the filename
img.save(name + '_blur' + extension)
# Save the image as a BMP
img.save(name + '.bmp')
I've tried a bunch of other stuff, but this code is the closest I've gotten. Thanks so much for your help.
I tried your code. I actually get:
NameError: name 'filepath' is not defined
because you have a filepath which should be entry.path:
(name, extension) = os.path.splitext(entry.path)
Besides this, your code works, except that you have both images blurred. The last line:
img.save(name + '.bmp')
is cleary not needed, it overwrites the original images with the blurred ones.

Image segmentation using corresponding masks in python

I have corresponding masks to the images that I want to segment.
I put the images in one folder and their corresponding masks in another folder.
I'm trying to apply those masks or multiply them by the images using two for loops in python to get the segmented images.
I'm using the code below:
def ImageSegmentation():
SegmentedImages = []
for img_path in os.listdir('C:/Users/mab/Desktop/images/'):
img=io.imread('C:/Users/mab/Desktop/data/'+img_path)
for img_path2 in os.listdir('C:/Users/mab/Desktop/masks/'):
Mask = io.imread('C:/Users/mab/Desktop/masks/'+img_path2)
[indx, indy] = np.where(Mask==0)
Color_Masked = img.copy()
Color_Masked[indx,indy] = 0
matplotlib.image.imsave('C:/Users/mab/Desktop/SegmentedImages/'+img_path2,Color_Masked)
segs.append(Color_Masked)
return np.vstack(Color_Masked)
This code works when I try it for a single image and a single mask (without the folders and loops).
However, when I try to loop over the images and masks I have in the two folders, I get output images that are segmented by the wrong mask (not their corresponding mask).
I can't segment each single image alone without looping because I have more than 500 Images and their masks.
I don't know what I'm missing or placing wrong in this code and how can I fix it? Also, is there an easier way to get the segmented images?
Unless I have grossly misunderstood, you just need something like this:
import glob
filelist = glob.glob('C:/Users/mab/Desktop/images/*.png')
for i in filelist:
mask = i.replace("images","masks")
print(i,mask)
On my iMac, that sort of thing produces:
/Users/mark/StackOverflow/images/b.png /Users/mark/StackOverflow/masks/b.png
/Users/mark/StackOverflow/images/a.png /Users/mark/StackOverflow/masks/a.png

How to save multiple outputs after reading multiple inputs in Python

i am reading .png images from a folder and doing some operations and i want to save those images in an order like Img1.png, Img2.png, Img3.png.... i tried to use this code :
cv2.imwrite("Img{}.png".format(i),Image)
but it keeps overriding single image.
below is the code:
def main(path):
i=0
image = cv2.imread(path)
#do some operations on image
cv2.imwrite('Img{}.png'.format(i),image)
i=i+1
cv2.waitKey(0)
The path contains multiple .png images so when main executes it resets the value of 'i' and output is overridden.
I suppose it's because of the type of formatting. The old python uses '%s %s' % ('one', 'two')format, did you try this formatting?
I suppose that path - space separated:
path = "im1.png imre.png lena.jpg"
it seams so:
path_lst = path.split(' ')
for i, path_i in enumerate(path_lst):
image = cv2.imread(path_i)
#do some operations on image
cv2.imwrite('Img{}.png'.format(i),image)
all works. Idk - why they gave me "-" =D

python PIL acces multiple images from a single image file

I have written a python script to Delta compress an image. The image file format is .tif which contains 8 images. When I use the normal code ...
org_Image = Image.open(image)
org_Data = org_Image.load()
... I can only access the first image. How do I go about accessing the other ones?
You use org_Image.seek(org_Image.tell() + 1) to get the next one.
In PIL seek moves you to a given frame, (with an IO_Error if it doesn't exist), and tell reports the current frame number.

Categories

Resources