0

I'm using python and working on image processing. I'm using opencv to get the only green colour out of the image and count its pixels green & black, but only for one image. Like in the script below, how can I apply the loop in the script to do for several(100+) images.

import cv2
import numpy as np
## Read
img = cv2.imread("camera/2018-11-25_0116.jpg")
## convert to hsv
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)


## mask of green (36,0,0) ~ (70, 255,255)
mask = cv2.inRange(hsv, (50, 50, 50), (70, 255,255))

## slice the green
imask = mask>0
green = np.zeros_like(img, np.uint8)
green[imask] = img[imask]

cv2.imwrite("2018-11-25_0116.jpg", green)

from PIL import Image
im = Image.open('2018-11-25_0116.jpg')

black = 0
green = 0

for pixel in im.getdata():
    if pixel == (0, 0, 0): # if your image is RGB (if RGBA, (0, 0, 0, 255) or so
        black += 1
    else:
        green += 1
print('black=' + str(black)+', green='+str(green))

1 Answers1

0

os.walk should solve your problem.

import cv2
import numpy as np
## Read
for root, dirnames, filenames in os.walk(source):
    for filename in filenames:
            matches.append(os.path.join(root, filename))
for match in matches:
    img = cv2.imread(match)
## convert to hsv

Something like that would work. Do not forget to define source variable. It will be your directory.

nerdicsapo
  • 427
  • 5
  • 16
  • I'm able to achieve the desired result of converting every image into black & green but output is over writing the same file instead of creating a separate file for each corresponding image – Kopal Chaudhary Dec 04 '18 at 11:03
  • from glob import glob for fn in glob('camera/*.jpg'): img = cv2.imread(fn) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, (50, 50, 50), (70, 255,255)) imask = mask>0 green = np.zeros_like(img, np.uint8) green[imask] = img[imask] cv2.imwrite("*.jpg", green) ch = cv2.waitKey() if ch == 100: break cv2.destroyAllWindows() – Kopal Chaudhary Dec 04 '18 at 11:04
  • I do not know if I understand your question correct, you have to change parameters of cv2.imwrite method. You do this with simple string operations, like adding prefix. like, fn = fn + "_edited_image.jpg" and then pass it to imwrite method. – nerdicsapo Dec 04 '18 at 11:28