Apply bitwise operation two different folders in python - python

I'm trying to combine all images one by one from two different folders, for example, I have those two folders
-folder1
-+img1.jpg
-+img2.jpg
-+img3.jpg
...
-folder2
-+img_1.jpg
-+img_2.jpg
-+img_3.jpg
what I would like to do is apply bitwise operation to img1.jpg and img_1.jpg, img2.jpg and img_2.jpg ...
I'm trying with this code in google colab but no any output
Code is as follows:
import os
import cv2
import pathlib
from google.colab.patches import cv2_imshow
folder1=pathlib.Path("/content/drive/MyDrive/Healthy")
folder2=pathlib.Path("/content/drive/MyDrive/mask_Healthy")
for filename in os.listdir(folder1):
for filename2 in os.listdir(folder2):
if (filename == filename2):
img1 = cv2.imread(os.path.join(folder1,filename),cv2.IMREAD_UNCHANGED)
img1 = cv2.resize(img1,(224, 224))
img2 = cv2.imread(os.path.join(folder2,filename2),cv2.IMREAD_UNCHANGED)
img2 = cv2.resize(img2,(224, 224))
dest_and = cv2.bitwise_and(img2,img1,mask = None)
cv2_imshow(dest_and)
make_dir(os.path.join("segmented", "seg", cv2.imwrite('filename.jpg',dest_and )))

Related

images to np array and keep the order

I am trying to take 1967 jpg images to a np array with following codes. How do I keep the original order of the images in the array?
import cv2
import glob
import numpy as np
X_data = []
files = glob.glob ("/content/drive/My Drive/CourseWork/images/emotionet_validation/*.jpg")
for myFile in files:
print(myFile)
image = cv2.imread (myFile)
X_data.append (image)
print('X_data shape:', np.array(X_data).shape)
https://docs.python.org/3/howto/sorting.html
import cv2
import glob
import numpy as np
X_data = []
files = glob.glob ("/content/drive/My Drive/CourseWork/images/emotionet_validation/*.jpg")
sorted(files)
## Do you need sort to ignore case?
## sorted(files, key=str.casefold)
for myFile in files:
print(myFile)
image = cv2.imread (myFile)
X_data.append (image)
print('X_data shape:', np.array(X_data).shape)

Merging images from different folders and storing to a different folder

I have three different folders m1, m2, and m3. The 'm1' folder contains images of the format image(i)_m1.png (where i =1 to N), 'm2' folder contains images of the format image(i)_m2.png, and 'm3' folder contains images of the format image(i)_m3.png. I want to merge these images using cv2.merge like this:(cv2.merge((image1_m1, image1_m2, image1_m3)) and it continues for N times and get stored in a different folder than contains 'N' merged images of the format image(i)_merged.png.
import pandas as pd
import cv2
import numpy as np
import glob
import os
filenames1 = glob.glob("data_folder/m1/*.png")
filenames1.sort()
filenames2 = glob.glob("data_folder/m2/*.png")
filenames2.sort()
filenames3 = glob.glob("data_folder/m3/*.png")
filenames3.sort()
for f1 in filenames1:
for f2 in filenames2:
for f3 in filenames3:
img1 = cv2.imread(f1)
img2 = cv2.imread(f2)
img3 = cv2.imread(f3)
img_m1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
img_m2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
img_m3 = cv2.cvtColor(img3, cv2.COLOR_BGR2GRAY)
img_rgb = cv2.merge((img_m1, img_m2, img_m3))
cv2.imwrite("data_folder/merge/img_name.png", img_rgb)
Your question is not complete. I assume you have a problem with for loop.
You might replace the nested for loops with this:
for f1,f2,f3 in zip(filenames1,filenames2,filenames3):

Write an array of Dicom images

I have a folder of dicom images and I stored these images in an array and I would like to print them out in a different folder.
I cannot find a method that will write out each of the images like the cv2.imwrite
import pydicom
import skimage, os
import numpy as np
FolderPathName = r'FolderPathName'
slices = [pydicom.read_file(FolderPathName + imagename) for imagename in os.listdir(FolderPathName)]
# Sort the dicom slices in their respective order
slices.sort(key=lambda x: int(x.InstanceNumber))
for x in range(len(slices)):
#write the images in a new folder
Method 1:
In your case,
The answer is ...
import pydicom
import skimage, os
import numpy as np
FolderPathName = r'FolderPathName'
slices = [pydicom.read_file(FolderPathName + imagename) for imagename in os.listdir(FolderPathName)]
# Sort the dicom slices in their respective order
slices.sort(key=lambda x: int(x.InstanceNumber))
jpg_folder = '' # Set your jpg folder
for idx in range(len(slices)):
#write the images in a new folder
jpg_filepath = os.path.join( jpg_folder, "pic-{}.jpg".format(idx) )
np_pixel_array = slices[idx].pixel_array
cv2.imwrite(jpg_filepath, np_pixel_array)
Method 2:
But, there is better way to process dicom files ...
import pydicom
import os
import numpy as np
import cv2
dicom_folder = '' # Set the folder of your dicom files that inclued images
jpg_folder = '' # Set the folder of your output folder for jpg files
# Step 1. prepare your input(.dcm) and output(.jpg) filepath
dcm_jpg_map = {}
for dicom_f in os.listdir(dicom_folder):
dicom_filepath = os.path.join(dicom_folder, dicom_f)
jpg_f = dicom_f.replace('.dcm', '.jpg')
jpg_filepath = os.path.join(jpg_folder,jpg_f)
dcm_jpg_map[dicom_filepath] = jpg_filepath
# Now, dcm_jpg_map is key,value pair of input dcm filepath and output jpg filepath
# Step 2. process your image by input/output information
for dicom_filepath, jpg_filepath in dcm_jpg_map.items():
# convert dicom file into jpg file
dicom = pydicom.read_file(dicom_filepath)
np_pixel_array = dicom.pixel_array
cv2.imwrite(jpg_filepath, np_pixel_array)
In above code,
the Step 1 is focus on file path processing. It's good for your to porting your code into different environment easily.
The Step 2 is major code which focus on any kind of image processing.

Reading Multiple tiff files in python from a folder

I have a folder containing 10K tiff files, how can i import all the files using python so that i can do some predictive modelling.
thanks
NK
Use the following approach:
import os
from PIL import Image
import numpy as np
dirname = 'tiff_folder_path'
final = []
for fname in os.listdir(dirname):
im = Image.open(os.path.join(dirname, fname))
imarray = np.array(im)
final.append(imarray)
final = np.asarray(final) # shape = (60000,28,28)

How to convert multiple RGB images in one folder to grayscale in python

Someone could help me please, I want to convert my RGB images in one folder to grayscale at one time. I've been looking for some Python codes but haven't found any. I tried to do as following but it didn't work.
Here is my code:
from skimage.color import rgb2gray
from skimage.io import imread, imsave
from skimage.filters import threshold_otsu
from skimage import img_as_uint
inp_image = imread("C:/RGB/*.JPG")
img_gray = rgb2gray(inp_image)
thresh = threshold_otsu(img_gray)
binary_thresh_img = img_gray & gt; thresh
imsave("C:/Grayscale", img_as_uint(binary_thresh_img))
And it gave me following error:
OSError: [Errno 22] Invalid argument: 'C:/RGB/*.JPG'
You can get the list with the filenames with glob().
import glob
for filename in glob.glob("C:/RGB/*.JPG"):
inp_image = imread(filename)
[...]
To add to the list of solutions:
import os
from PIL import Image
ORIGIN_PATH = "./folder1/"
DESTIN_PATH = "./folder2/"
for filename in os.listdir(ORIGIN_PATH):
img = Image.open(ORIGIN_PATH + filename).convert("LA")
img.save(DESTIN_PATH + filename)

Categories

Resources