1.图片保存在指定目录
在opencv中用于保存图片所用到的语句是cv2.imwrite(filepath,image)
filepath是用于保存的地址路径(可用绝对和相对路径),此路径必须真实存在。如果不存在,则可以通过os模块创建,也就是说在后面一排加上os.makedirs(os.path.dirname(filename), exist_ok=True),这里的filename指的是filepath指向的文件。
1.1实际实例
import cv2
import os
import numpy as np
class TestLoader:
# imdb image_path(list)
def __init__(self, imdb, batch_size=1, shuffle=False):
self.imdb = imdb
self.batch_size = batch_size
self.shuffle = shuffle
self.size = len(imdb) # num of data
# self.index = np.arange(self.size)
self.cur = 0
self.data = None
self.label = None
self.reset()
self.get_batch()
def reset(self):
self.cur = 0
if self.shuffle:
# shuffle test image
np.random.shuffle(self.imdb)
def iter_next(self):
return self.cur + self.batch_size <= self.size
# realize __iter__() and next()--->iterator
# return iter object
def __iter__(self):
return self
def __next__(self):
return self.next()
def next(self):
if self.iter_next():
self.get_batch()
self.cur += self.batch_size
return self.data
else:
raise StopIteration
def getindex(self):
return self.cur / self.batch_size
def getpad(self):
if self.cur + self.batch_size > self.size:
return self.cur + self.batch_size - self.size
else:
return 0
def get_batch(self):
imdb = self.imdb[self.cur]
'''
cur_from = self.cur
cur_to = min(cur_from + self.batch_size, self.size)
#picked image
imdb = [self.imdb[self.index[i]] for i in range(cur_from, cur_to)]
# print(imdb)
'''
# print type(imdb)
# print len(imdb)
# assert len(imdb) == 1, "Single batch only"
im = cv2.imread(imdb)
self.data = im
path = "F:/Dataset/MTCNN_DATA/test/" # 保存测试图片的地方
gt_imdb=[]
for item in os.listdir(path):
gt_imdb.append(os.path.join(path,item))
test_data = TestLoader(gt_imdb)
count = 0
for imagepath in gt_imdb:
print(imagepath)
image = cv2.imread(imagepath)
save_path = 'D:/pycharm/test/' # 图片保存的路径
count += 1
cv2.imwrite(save_path+'%d.jpg'%(count),image)
# os.path.dirname(path)
# 语法:os.path.dirname(path)
# 功能:去掉文件名,返回目录
os.makedirs(os.path.dirname(save_path),exist_ok=True)
运行结果:
2.文件夹里所有图片以数组形式输出
2.1实际代码
import os
import cv2
import numpy as np
def read_pic(path):
if os.path.exists(path):
print(1)
else:
print(2)
dirnames = sorted(os.listdir(path))
# print(dirname)
n = len(dirnames)
print(n)
# f = open('neg.txt', 'w')
Srcimg= []
for dirname in dirnames:
# print("正在读取第%d张图片" % i)
# fromfile()函数读回数据时需要用户指定元素类型,并对数组的形状进行适当的修改,indecode下中文路径也可以运行
img = cv2.imdecode(np.fromfile(path + dirname, dtype=np.uint8), -1)
#####保存图片#########
cv2.imwrite(output_path + "/" + dirname, img)
img_path = os.path.join(input_path, dirname)
# f.write(img_path+'\n')
Srcimg.append(img)
# cv2.imshow('pic',img)
# cv2.waitKey(0)
# print(img_path)
Srcimg = np.array(Srcimg)
return Srcimg
if __name__ == '__main__':
input_path='D:/pycharm/10kinds-light-face-detector-align-recognition-master/test/'
output_path='D:/pycharm/compare_three_module/result/'
Srcimg=read_pic(input_path)
print(Srcimg)
运行结果: