【发布时间】:2019-05-01 17:26:31
【问题描述】:
我想使用 opencv 对整个图像数据集进行阈值处理,并将阈值图像保存在同一目录中。我怎么做?我尝试了一种方法(下面的代码),但它显示以下错误:TypeError: img is not a numpy array or scalar。 任何帮助将不胜感激
import argparse
import cv2
import numpy as np
import os
from imutils import paths
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True,
help= "Path to test dataset")
ap.add_argument("-t", "--threshold", type = int, default = 128,
help = "Threshold value")
args = vars(ap.parse_args())
test_path =os.path.sep.join([args["dataset"]])
TestPath = list(paths.list_images(test_path))
idxs = np.arange(0, len(TestPath))
images = []
path_to_save = "C:/Desktop/Python Training/test"
def main():
for i in idxs:
image = cv2.imread(test_path[i])
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.resize(image, (200, 200))
image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY)
images.append(image)
return (np.array(images))
cv2.imwrite(path_to_save, images)
cv2.waitKey(0)
if __name__ == '__main__':
main()
【问题讨论】:
-
顺便说一句,您实际上并不需要编写任何 Python 来对一堆图像进行灰度、调整大小和阈值处理。您可以像这样在命令行中使用 ImageMagick
mkdir results; magick mogrify -colorspace gray -resize 200x200! -threshold 50% -path results *.png