首页 > 解决方案 > opencv 图像的自定义名称(复杂名称)

问题描述

嗨,我想从相机中取出一帧并将其保存在“图像”文件夹中,我希望图像具有名称+当前时间戳+.jpg,我输入这样的错误:

cv2.imwrite(os.path.join(path2 , rn), img)

我在哪里path2='images' 得到rn=str(rightnow.strftime("%I:%M:%p")) 这个错误: could not find a writer for the specified extension in function 'cv::imwrite_'

我该怎么做,我搜索但没有找到答案,我是 python 新手,在此先感谢

标签: pythonopencvoperating-system

解决方案


接受的答案是os具体的。

如果在 Windows 中运行代码会发生什么?

假设你有数百万个代码,你打算用 改变每个斜线/\

您应该使用os.path.sep而不是静态斜杠声明。

  • 首先,删除:in strftime,你可以使用-or _or nothing 。

    • rn = str(rightnow.strftime("%I%M%p"))
      
  • 其次,检查路径是否存在,如果不存在,则创建。

    • path3 = "".join([path2, os.path.sep, rn])
      
      if not os.path.exists(path3):
          os.mkdir(path3)
      
  • 三、创建镜像名称

    • save = "".join([path3, os.path.sep, "image_name.png"])
      
    • 如果您在循环内执行语句,则可以使用 counter

      • counter += 1
        save = "".join([path3, os.path.sep, "image_name{}.png".format(counter)])
        

代码:


import os
import cv2
from datetime import datetime

path2 = 'img2'
rightnow = datetime.now()
rn = str(rightnow.strftime("%I%M%p"))
img = cv2.imread("1.png")

path3 = "".join([path2, os.path.sep, rn])

if not os.path.exists(path3):
    os.mkdir(path3)

save = "".join([path3, os.path.sep, "image_name.png"])

cv2.imwrite(save, img)

推荐阅读