在python opencv模块中编辑后保存同名图像

Posted

技术标签:

【中文标题】在python opencv模块中编辑后保存同名图像【英文标题】:Save an image with the same name after editing in python opencv module 【发布时间】:2021-03-02 18:06:57 【问题描述】:

我正在尝试在 opencv 上编辑后保存具有相同名称的图像。我可以用相同的名字保存。但我不能保存在不同的文件中。所以,这是我的代码:

import cv2
import numpy as np
import glob

filename = [img for img in glob.glob("./mypath_1/*.jpg")]
flist=sorted(filename)
images = []
path='./mypath_2/'

for image in flist:
    img= cv2.imread(image)
    alpha=2
    beta=-420

    img2=cv2.addWeighted(img,alpha,np.zeros(img.shape,img.dtype),0,beta)
    hsv = cv2.cvtColor(img2, cv2.COLOR_BGR2HSV)
    cv2.imwrite( path+image, hsv)

另外,我试过这个:cv2.imwrite( './mypath_2/'+image, hsv)

我没有保存图像,并且此代码中没有消息错误。

有什么建议吗?

【问题讨论】:

【参考方案1】:
import numpy as np
import cv2
import os
import sys
from pathlib import Path

if __name__ == "__main__":
    #get alpha and beta values
    alpha, beta =2, -420
    # get directory path where the images are stored
    image_dir = "/path/to/image read directory/"
    # get directory path where you want to save the images
    output_dir = "/path/to/image write directory/"
    #iterate through all the files in the image directory
    for _, _, image_names in os.walk(image_dir):
        #iterate through all the files in the image_dir
        for image_name in image_names:
            # check for extension .jpg
            if '.jpg' in image_name:
                # get image read path(path should not contain spaces in them)
                filepath = os.path.join(image_dir, image_name)
                # get image write path
                dstpath = os.path.join(output_dir, image_name)
                print(filepath, dstpath)
                # read the image
                image = cv2.imread(filepath)
                # do your processing
                image2 = cv2.addWeighted(image, alpha,np.zeros_like(image),0,beta)
                hsv = cv2.cvtColor(image2, cv2.COLOR_BGR2HSV)
                # write the image in a different path with the same name
                cv2.imwrite(dstpath, hsv)
                print(image.shape, image2.shape, hsv.shape)

【讨论】:

【参考方案2】:

您可以使用 nipath 使用 3 行代码完成此操作

import ntpath
filename = ntpath.basename("D:\coding\python\Sample Photos\1.jpg")
cv2.imwrite("D:\coding\python\Sample Photos\"+filename, img)

【讨论】:

以上是关于在python opencv模块中编辑后保存同名图像的主要内容,如果未能解决你的问题,请参考以下文章

python如何保存img文件

openCV—Python——载入显示和保存图像

python去除rpm仓库中同名低版本的包

用Python编写录屏程序将播放的视频用截屏方法转换为多帧图像编辑后保存为GIF格式动图文件

用Python编写录屏程序将播放的视频用截屏方法转换为多帧图像编辑后保存为GIF格式动图文件

Python使用opencv基于坐标范围批量剪裁(图像)并将剪裁后的图像保存到指定的新文件夹中