#Python#Tools#png转jpg

Tools:

png文件较大,用于网络训练占用内存过大,可以转换为占用内存较小的有损压缩格式jpg

从指定csv读取png文件,然后将其保存到其他路径下同名jpg文件

import cv2 as cv 
from PIL import Image
import os 
import csv
import re 

filePath ="/test/DataAnnotation/test.csv"



def PNG_JPG(PngPath,outFilepath):
    img = cv.imread(PngPath, 0)
    #print(img.shape)
    w, h = img.shape[::-1]
    infile = PngPath
    
    #os.path.splitext(“文件路径”)    分离文件名与扩展名
    outfile = os.path.splitext(outFilepath)[0] + ".jpg"
    img = Image.open(infile)
    # Image.NEAREST :低质量
    # Image.BILINEAR:双线性
    # Image.BICUBIC :三次样条插值
    # Image.ANTIALIAS:高质量
    #img = img.resize((int(w / 2), int(h / 2)), Image.ANTIALIAS)
    try:
        ##img.split() Return Value: It returns a tuple containing bands.
        if len(img.split()) == 4:
            # prevent IOError: cannot write mode RGBA as BMP
            r, g, b, a = img.split()
            #将提取的rgb组合新图片
            img = Image.merge("RGB", (r, g, b))
            img.convert('RGB').save(outfile, quality=70)
            #os.remove(PngPath)
        else:
            img.convert('RGB').save(outfile, quality=70)
            #os.remove(PngPath)
        return outfile
    except Exception as e:
        print("Transform error!", e)

if __name__ == "__main__":
    csvFile = open(filePath, "r")
    reader = csv.reader(csvFile)
    ##ssave to dict
    #result={}
    for item in reader:
        if reader.line_num ==1:
            continue
        #result[item[0]]=item[1]
        ####保存到新路径
        new_dir = re.sub("DataAnnotation","DataAnnotation_jpg",item[0])
        if not os.path.exists(new_dir):
            os.makedirs(new_dir)
        png_path = os.path.join(item[0],item[1])
        new_filepath = os.path.join(new_dir,item[1])
        print(png_path,new_filepath,sep="\n")
        PNG_JPG(png_path,new_filepath)
        
  

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import cv2 import numpy as np import torch from skimage.segmentation import slic from skimage.util import img_as_float # 读取A图像和B图像 img_a = cv2.imread(r'D:\Users\Administrator\PycharmProjects\pythonProject\my tools\super_pixel\1.png') img_b = cv2.imread(r'D:\Users\Administrator\PycharmProjects\pythonProject\my tools\super_pixel\2.jpg') # 换为浮点数 img_a = img_as_float(img_a) img_b = img_as_float(img_b) # 使用SLIC算法进行超像素分割 segments_a = slic(img_a, n_segments=1000, compactness=10) segments_b = slic(img_b, n_segments=1000, compactness=10) # 计算A图像的超像素范围 segment_ids = np.unique(segments_a) segment_ranges = [] for segment_id in segment_ids: y, x = np.where(segments_a == segment_id) min_x, max_x = np.min(x), np.max(x) min_y, max_y = np.min(y), np.max(y) segment_ranges.append((min_x, min_y, max_x, max_y)) # 创建A图像的超像素范围图 segment_map_a = np.zeros_like(segments_a, dtype=np.int32) for i, segment_range in enumerate(segment_ranges): min_x, min_y, max_x, max_y = segment_range segment_map_a[min_y:max_y+1, min_x:max_x+1] = i # 使用A图像的超像素范围索引对B图像进行分割 segment_map_b = np.zeros_like(segments_b, dtype=np.int32) for i, segment_range in enumerate(segment_ranges): min_x, min_y, max_x, max_y = segment_range segment_id = segments_a[min_y, min_x] y, x = np.where(segments_b == segment_id) segment_map_b[y, x] = i # 换为PyTorch张量 segment_map_b = torch.Tensor(segment_map_b).long() # 显示B图像的超像素范围图 cv2.imshow('Segment Map', segment_map_b.numpy()) cv2.waitKey(0) cv2.destroyAllWindows()。上述代码出现错误: cv2.imshow('Segment Map', segment_map_b.numpy()) cv2.error: OpenCV(4.7.0) D:/a/opencv-python/opencv-python/opencv/modules/highgui/src/precomp.hpp:155: error: (-215:Assertion failed) src_depth != CV_16F && src_depth != CV_32S in function 'convertToShow'
06-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值