我正在使用python并致力于图像处理。我正在使用opencv从图像中获取唯一的绿色并计数其像素为绿色和黑色,但仅用于一张图像。就像下面的脚本一样,如何在脚本中应用循环以处理几张(100+)张图像。
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))
答案 0 :(得分:0)
os.walk应该可以解决您的问题。
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
类似的事情会起作用。不要忘记定义源变量。这将是您的目录。