欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

随机移动n个图片到另一文件夹

程序员文章站 2022-06-15 19:46:34
#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time :2020/10/12 15:59# @Author :weiz# @ProjectName :yoloProcessedData# @File :randomImagesData.py# @Description :随机抽取数据import osimport randomimport sysimport cv2sys.setrecursion....
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time        :2020/10/12 15:59
# @Author      :weiz
# @ProjectName :yoloProcessedData
# @File        :randomImagesData.py
# @Description :随机抽取数据
import os
import random
import sys
import cv2
sys.setrecursionlimit(1000000)    # 设置递归深度,深度越大,要求电脑的内存就越大


class CreateRandomPage:
    """
    在区间[begin, end)中随机产出不重复的needCount数
    eg:
        a = CreateRandomPage(0, -10, 20)
        print(a.createRandomPage())
    """
    def __init__(self, begin, end, needCount):
        if begin > end:
            print("There is a problem with the interval size setting!")
            self.begin = end
            self.end = begin - 1
        else:
            self.begin = begin
            self.end = end - 1

        if needCount > (self.end - self.begin):
            print("The number generated is greater than the number of interval ranges!")
            self.needCount = self.end - self.begin + 1
        else:
            self.needCount = needCount
        self.resultList = []
        self.count = 0

    def createRandomPage(self):
        tempInt = random.randint(self.begin, self.end)
        if(self.count < self.needCount):
            if(tempInt not in self.resultList):
                self.resultList.append(tempInt)      #将长生的随机数追加到列表中
                self.count += 1
            return self.createRandomPage()           #在此递归
        return self.resultList


def randomImg(srcImagePath, saveImagePath, num, isChangeFilerName=True):
    """
    随机在srcImagePath文件中取num个图片放置到saveImagePath中
    :param srcImagePath:
    :param saveImagePath:
    :param num:
    :param isChangeFilerName:是否添加图片文件夹的名字
    :return:
    """
    folderName = srcImagePath.split("/")[-1]
    imgsList = os.listdir(srcImagePath)
    randomObject = CreateRandomPage(0, len(imgsList), num)
    randomNumList = randomObject.createRandomPage()
    print(len(randomNumList))
    for index in randomNumList:
        imgPath = os.path.join(srcImagePath, imgsList[index])
        saveImgName = ""
        if isChangeFilerName:
            tmp = folderName + "_" + imgsList[index].split('.')[0] + ".png"
            saveImgName = os.path.join(saveImagePath, tmp)
        else:
            saveImgName = os.path.join(saveImagePath, imgsList[index])
        img = cv2.imread(imgPath)
        cv2.imwrite(saveImgName, img)


srcImages = "D:/dataSet/imgs/011"
saveImages = "C:/Users/weiz/Desktop/sourceImages"
if __name__ == "__main__":
    randomImg(srcImages, saveImages, 263) 

本文地址:https://blog.csdn.net/qq_31112205/article/details/109032579

相关标签: 数据处理 Python