Binarize a set of images in Python - python

I would like to binarize a set of images that are situated in a particular directory on my computer.
I have succeeded to do it for a single image but I would like to run it automatically for all the images that are in the folder.
Here is the code that I have tried to implement :
path = r'C:\Users\Antonin\Desktop\WISSEM\IMAGES_20210303\Samplings'
arr = os.listdir(path)
for i in range(len(arr)):
file = arr[i]
### We read the grayscale image avec cv2
im_gray = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
### We binarize the image
(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
### We save the binarized image
cv2.imwrite('binary_image_2.tiff', im_bw)
How can I modify the code in order to binarize each image situated in my folder, because for the moment I am not sure about the procedure in order to do so :
Binarize each image in the folder.
Save each binarized image as a new image in the same folder
Could you help me please with this issue,
Thank you a lot,

Use the result of the os.listdir().
Python allows iterating over lists/arrays with its for loop directly.
path = r'C:\Users\Antonin\Desktop\WISSEM\IMAGES_20210303\Samplings'
arr = os.listdir(path)
# iterate over every element in the directory
# file contains the filename
for file in arr:
filename = file.split('.')[0]
# do to binary …
# save as tiff with the same name but different extension
cv2.imwrite(f'{filename}.tiff', im_bw)

Related

How can I add features from different images and merge them into a final image

I have some input images which have the same dimensions, each of which may contain one or more blobs. I know how to load the image and convert it to binary but I want to be able to add all found blobs from any amount of images and paste them into a final image (which will start out blank) and be the same size as one of the input images. This is not an attempt to stitch images or concatenate them horizontally.
I don't know if opencv or pillow is better for this as I have very little experience or knowledge in feature extraction.
Code
import cv2
# use cv2 imread method to load image
img1 = cv2.imread("im1.jpg")
img2 = cv2.imread("im2.jpg")
# make bw image
im1_gray = cv2.imread("im1.jpg", cv2.IMREAD_GRAYSCALE)
im2_gray = cv2.imread("im2.jpg", cv2.IMREAD_GRAYSCALE)
# get threshold and binary image
(thresh, im_bw1) = cv2.threshold(im1_gray, 128, 255,
cv2.THRESH_BINARY | cv2.THRESH_OTSU)
# save binary image 1
im_out1 = "bw_image_1"
ext = ".png"
im_name = im_out1 + "_" + str(thresh) + ext
cv2.imwrite(im_name, im_bw1)
# get threshold and binary image
(thresh, im_bw2) = cv2.threshold(im1_gray, 128, 255,
cv2.THRESH_BINARY | cv2.THRESH_OTSU)
# save binary image 2
im_out2 = "bw_image_2"
ext = ".png"
im_name = im_out2 + "_" + str(thresh) + ext
cv2.imwrite(im_name, im_bw2)
Input images
Desired output
I don't know how to do this manually, but the output for this would be either a white or grey background with two black blobs in it.
If either of the input images had two blobs in it and the other image had three blobs the output image would have five blobs, with positions equal to that of their position in the original image(s), it does not matter if they overlap.
This has been asked before on opencv c++, there should be the same function on python3, hconcat, placing two images side by side, opencv 2.3, c++

Why imwirte function writes my images in BGR order?

I am trying to read images in a folder and save them after doing some processes.
I using following code to save my images:
import cv2
i = 0
while i < len(bright_images):
cv2.imwrite(f'/path/image_{i}.png', cv2.cvtColor(bright_images[i],cv2.COLOR_BGR2RGB)
i += 1
But the problem is that when writing images all red colors in my images turn to be blue, colors change completely, it seems as if it saves based on BGR color instead of RGB.
How do I fix this issue?
FYI, I am reading images using this code:
def load_images(path):
image_list=[]
images= glob.glob(path)
images = natsorted(images)
for index in range(len(images)):
image= cv2.cvtColor(cv2.imread(images[index]),cv2.COLOR_BGR2RGB)
image_list.append(cv2.resize(image,(1920,1080)))
return image_list

I can't change my RGB colour into grayscale images in python using CV

So, I am doing this project to detect diabetic retinopathy using deep learning. I however am stuck in the preprocessing image section as the pictures that are in different folders(for diff stages of DR) wouldn't convert into grayscale nomatter how much I try.
Here is my functions that does the early preprocessing stage:
def preprocessing(conditionname,directory):
for image in os.listdir(directory):
label = eye_label(conditionname,image)
path = os.path.join(directory,image)
image = cv2.imread(path,cv2.IMREAD_COLOR) #Reading the colour images
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #Changing coloured image into black and white
#image = cv2.addWeighted(image,10,cv2.GaussianBlur(image , (0,0) , sigma_x) ,-4 ,12)
image = cv2.resize(image,(image_size,image_size)) #Changing the size of each image
return image
Try using your debugger or IDE to check everything gives you the result you expect, one step at a time.
If you load an image, print its shape:
img = cv2.imread(...)
print(image.shape)
If you convert an image to greyscale, check it has 1 channel afterwards:
img = cv2.cvtColor(...)
print(image.shape)
If you resize an image, check its size is what you expect:
img = cv2.resize(...)
print(image.shape)
If you are going to return an image from a function, check its size and type:
print(result.shape, result.dtype)
return result

Read files from a list of paths

I have downloaded a dataset for a deep learning project that contains images (.png) and the corresponding label for each image (.txt). I have all the images' paths in a list x. I want to iterate through these paths, preprocess the images using cv2, and append the new images to a new list images_data. However, every time I try to loop through it, I keep getting this same error: cv2.error: OpenCV(4.1.1) /io/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'
Even when I comment out that line of code that throws the error, I get another error when trying to resize the image.
This is the for loop I'm using to iterate through the list:
images_data = []
for file in x:
img = cv2.imread(file)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.resize(img, (80, 80))
images_data.append(img)
My x list looks pretty much like this:
x = [car1.png, car2.png, car3.png, car4.png, car5.png]
How can I solve this error?
That error indicates your img variable is empty so cv2.imread(file) did not read an image. You can check this after reading the image and before converting the color or resizing, with a simple if case:
if img is None:
print('Error reading image')
else:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
or check if the file exists using the os module:
img = cv2.imread(file)
if os.path.isfile(file):
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
os.path.isfile(file) will return True if the file exists.
I am assuming your files, car1.png, car2.png etc are in a different folder and not in the same path with this script in which case, you need to append the directory of the images to the file name before you can read it. So for example, if your images are in, let's say, '/home/Deep_Learning/Car_Images/' then when reading the images, the variable file must contain the string: /home/Deep_Learning/Car_Images/car1.png, for the first image and not just car1.png. You can do this using python's os module like this:
import cv2
import os
# Directory of the images. Change it according your path
data_dir = '/home/Deep_Learning/Car_Images/'
images_data = []
for file in x:
file_name = os.path.join(data_dir, file) # Append the image folder with the image name
if os.path.isfile(file_name) is False: #Check if image file exists
print("Image file ", file_name, "does not exist")
else:
img = cv2.imread(file_name)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.resize(img, (80, 80))
images_data.append(img)

OpenCV and rawkit python

I load a cr2 file in argv... then I want to convert it to an opencv format so i can use it in the app (not save it as a file). It is loaded first with Rawkit.
raw_image = Raw(sys.argv[1])
buffered_image = np.array(raw_image.to_buffer())
image = Image.frombytes('RGB', (raw_image.metadata.width, raw_image.metadata.height), buffered_image)
image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
That is my attempt.
The image loads and looks very poor with a bunch of diagonal zigzags
In essence :I need to convert
image = Image.frombytes('RGB', (raw_image.metadata.width, raw_image.metadata.height), buffered_image)
to the same format as what it would be if i used
image = cv2.imread(imagePath)
It may be easier if you use rawpy:
import rawpy
import cv2
raw = rawpy.imread("path/to/file") # access to the RAW image
rgb = raw.postprocess() # a numpy RGB array
image = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR) # the OpenCV image
cv2.imwrite("foo.png", image)
I just tried it and it worked without a problem.

Categories

Resources