Ask Your Question

Revision history [back]

How to loop over several images in opencv?

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))

How to loop over several images in opencv?

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))