Converting Images in a Folder to Grayscale Using Python and Opencv and Writing It to a Specific Folder

How to resize multiple images from a folder, convert them into grayscale and save them into another folder?

Try the following:

import cv2
import glob

for filename in glob.glob(r'your\path\*.png'):
print(filename)
img=cv2.imread(filename)
rl=cv2.resize(img, (500,500))
gray_image = cv2.cvtColor(rl, cv2.COLOR_BGR2GRAY)
cv2.imwrite(f'{filename}.resized.png', gray_image)

Convert entire folder to grayscale using image magick?

No need for Notepad. Start a Command Prompt and change directory to the one containing your images. So if your images are in HOME/Images, type:

cd Images

then press Enter/Return. Then type:

magick mogrify -colorspace gray *.png *.jpg

then press Enter/Return and you're finished.

Convert series of images into an array using OpenCV and convert the RGB array to gray scale

You can use os to read files from a folder. With the "endswith" function, you can extract file formats and pull them all.

Here is a working code

import numpy as np
import cv2 as cv
import os

for file in os.listdir("/mydir"): # images folder path
if file.endswith((".png",".jpg")): # you can add formats
img = cv.imread(file)
GS = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
th, Gray = cv.threshold(GS, 128, 192, cv.THRESH_OTSU)
cv.imwrite("converted-"+file,Gray)

Python script to convert RBG image dataset into Grayscale images using pillow

Probably this code would work for you?

Code:

import os
from PIL import Image
dir = '/content/pizza_steak/test/pizza'
for i in range(len(os.listdir(dir))):
# directory where images are stored
dir = '/content/pizza_steak/test/steak'

# get the file name
file_name = os.listdir(dir)[i]

# creating a final path
final_path = dir + '/' + file_name

# convet and save the image
Image.open(final_path).convert('L').save(f"/content/meow/gray{file_name}")

# uncomment this is you want to delete the file
# os.remove(final_path)

Converting an OpenCV Image to Black and White

Step-by-step answer similar to the one you refer to, using the new cv2 Python bindings:

1. Read a grayscale image

import cv2
im_gray = cv2.imread('grayscale_image.png', cv2.IMREAD_GRAYSCALE)

2. Convert grayscale image to binary

(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

which determines the threshold automatically from the image using Otsu's method, or if you already know the threshold you can use:

thresh = 127
im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]

3. Save to disk

cv2.imwrite('bw_image.png', im_bw)


Related Topics



Leave a reply



Submit