我想使用opencv对整个图像数据集进行阈值处理,并将阈值化的图像保存在同一目录中。我怎么做?我尝试了一种方法(下面的代码),但它显示以下错误:TypeError:img不是一个numpy数组或标量。 任何帮助将不胜感激
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()
答案 0 :(得分:0)
我没有使用os模块,而是使用了glob模块,并对main()函数进行了一些小的更改。下面是此代码
import argparse
import cv2
import glob
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())
path_to_save = "D:/downloads/"
def main():
i = 0
for filename in glob.glob(args['dataset']):
image = cv2.imread(filename)
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.resize(image, (200, 200))
ret, image = cv2.threshold(image, 150, 255, cv2.THRESH_BINARY)
cv2.imwrite(path_to_save + str(i) + '.jpg', image)
i += 1
if __name__ == '__main__':
main()
如果您熟悉glob,则必须知道如何赋予“数据集的路径”参数。如果没有,那么这是您应如何进行操作的示例:
-d“ D:/ downloads /*.*”表示获取指定文件夹中的所有文件(路径)
-d'D:/ downloads / *。jpg'表示仅抓取文件夹中的jpg文件