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):
Related
I've two binary files containing rgb pixes values. I would like to merge these two files into one big file.
I did this first:
img1 = np.fromfile("img1.rgb",dtype=np.uint8)
img2 = np.fromfile("img2.rgb",dtype=np.uint8)
img1 = np.reshape(img1,(1024,10000,3))
img2 = np.reshape(img2,(1024,10000,3))
out = np.empty((1024,20000,3))
out[:,:10000] = img1
out[:,-10000:] = img2
out.flatten().tofile("out.rgb")
The problem is that I load in memory the 2 images and also the resulting merge image.
Is it possible to do this without loading the images into memory ?
Maybe by using numpy memmap?
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 )))
I created an model in blender. From here I took 2d slices through the y-plane of that model leading to the following.
600 png files each corresponding to a ylocation i.e y=0, y=0.1 etc
Each png file has a resolution of 500 x 600.
I am now trying to merge the 600 pngs into a h5 file using python before loading the .h5 into some software. I find that each individual png file is read fine and looks great. However when I look at the final 3d image there is some stretching of the image, and im not sure how this is being created.
The images are resized (from 600x600 to 500x600, but I have checked and this is not the cause of the stretching). I would like to know why I am introducing such stretching in other planes (not y-plane).
Here is my code, please note that there is some work in progress here, hence why I append the dataset to a list (this is to be used for later code)
from PIL import Image
import sys
import os
import h5py
import numpy as np
import cv2
from datetime import datetime
dir_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(dir_path + '//..//..')
Xlen=500
Ylen=600
Zlen=600
directory=dir_path+"/LowPolyA21/"
for filename in os.listdir(directory):
if fnmatch.fnmatch(filename, '*.png'):
image = Image.open(directory+filename)
new_image = image.resize((Zlen, Xlen))
new_image.save(directory+filename)
dataset = np.zeros((Xlen, Zlen, Ylen), np.float)
# traverse all the pictures under the specified address
cnt_num = 0
img_list = sorted(os.listdir(directory))
os.chdir(directory)
for img in (img_list):
if img.endswith(".png"):
gray_img = cv2.imread(img, 0)
dataset[:, :, cnt_num] = gray_img
cnt_num += 1
dataset[dataset == 0] = -1
dataset=dataset.swapaxes(1,2)
datasetlist=[]
datasetlist.append(dataset)
dz_dy_dz = (float(0.001),float(0.001),float(0.001))
for j in range(Xlen):
for k in range(Ylen):
for l in range(Zlen):
if datasetlist[i][j,k,l]>1:
datasetlist[i][j,k,l]=1
now = datetime.now()
timestamp = now.strftime("%d%m%Y_%H%M%S%f")
out_h5_path='voxelA_'+timestamp+'_flipped'
out_h5_path2='voxelA_'+timestamp+'_flipped.h5'
with h5py.File(out_h5_path2, 'w') as f:
f.attrs['dx_dy_dz'] = dz_dy_dz
f['data'] = datasetlist[i] # Write data to the file's primary key data below
Example of image without stretching (in y-plane)
Example of image with stretching (in x-plane)
I'm working on a Parkinson dataset.
In my dataset folder, there are two folders :
In two of each, there are two other folders but that's really a detail:
in which...:
Now, in my code i'm doing a feature extraction and a label extraction here's my attempt:
(I've used the split function to get the name of the folder as you can tell in line 12.)
from imutils import paths
import numpy as np
import sys
import cv2
import os
import mahotas as mt
data =[]
np.set_printoptions(threshold=sys.maxsize)
pathswave=r'C:\Users\Bsi\Desktop\PFE2\Base2\dataset\wave'
imagePaths = list(paths.list_images(pathswave))
for imagePath in imagePaths:
label = imagePath.split(os.path.sep)[-2]
image = cv2.imread(imagePath)
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.blur(image,(3,3))
image = cv2.resize(image, (200, 200))
textures = mt.features.haralick(image)
feat = textures.mean(axis=0)
data.append(feat)
data.append(label)
print(np.array(data))
Here's a portion of the output:
Now is there any way to convert the two labels, 'parkinson' and 'healthy' to two distinct integers ( preferably 0 and 1, (1 being 'parkinson).
3 numbers, in case its not either :)
x = imagePath.split(os.path.sep)[-2]
label = '0' if x == 'healthy' else '1' if x == 'parkinsons' else '-1'
You might want to use a dictionary:
my_dict = {'healthy': 0, 'parkinsons': 1}
You can later get 0 or 1, by accessing the elements using get:
my_number=my_dict.get(label)
import pprint as pp
original_img = cv2.imread("/content/drive/My Drive/images/image1.jpg") #here i want to use multiple images atleast 250 images.
original_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)
results = tfnet2.return_predict(original_img)
print(results)
I guess all your images are in the folder images. So you can use os to gett all their filenames.
import os
pth = "/content/drive/My Drive/images" # make sure it is correct
images = os.listdir(pth)
for image in images:
image_path = os.path.join(pth, image)
original_img = cv2.imread(image_path)
original_img = cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)
results = tfnet2.return_predict(original_img)
print(results)
anyone can use for loop add empty folder to direct all the json files directly to the same folder using basic addition '+' operator.
for i in range():
original_img = cv2.imread("/folder path(500+ images)/" + any_empty_folder[i])