【问题标题】:How to write convert jpeg to png on python?如何在python上编写将jpeg转换为png?
【发布时间】:2020-08-03 14:18:22
【问题描述】:

我需要用 Python 编写脚本,例如带有选项的this

  • 启用 PNG 透明度
  • 将相似颜色视为透明。 5%

我该怎么做?

可能的解决方案

ffmpeg, imagemagick

【问题讨论】:

  • 欢迎来到 SO!请拨打tour,阅读How to Ask,并提供minimal reproducible example。你试过什么了?为什么您的解决方案不符合您的期望?
  • 你说“想把相似的颜色当作透明的5%”是什么意思?类似于什么? 5%是干什么用的?请给出一个示例输入和相应的输出图像,并展示你到目前为止所做的尝试。

标签: python image imagemagick-convert


【解决方案1】:

这是在 Python/OpenCV 中执行此操作的一种方法

  • 读取输入
  • 定义要透明的所需颜色(蓝色)
  • 定义容差量 (5%)
  • 根据容差创建颜色的上限和下限
  • 颜色和反转阈值
  • 将阈值结果放入输入的alpha通道
  • 保存结果

输入:

import cv2
import numpy as np

# load image
img = cv2.imread('barn.jpg')

# specify blue color
color = (230,160,120)
b = color[0]
g = color[1]
r = color[2]

# specify tolerance as percent
tol = 5
tol = 5/100

# make lower and upper bounds as color minus/plus 5%
bl = int((1-tol) * b)
gl = int((1-tol) * g)
rl = int((1-tol) * r)
lower = (bl,gl,rl)
bu = int((1+tol) * b)
gu = int((1+tol) * g)
ru = int((1+tol) * r)
upper = (bu,gu,ru)

# threshold on color and invert
mask = cv2.inRange(img, lower, upper)
mask = 255 - mask

# put mask into alpha channel
result = img.copy()
result = cv2.cvtColor(result, cv2.COLOR_BGR2BGRA)
result[:, :, 3] = mask

# save resulting masked image
cv2.imwrite('barn_transp_blue.png', result)

# display result, though it won't show transparency
cv2.imshow("MASK", mask)
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

阈值图像:

透明结果:

【讨论】:

    【解决方案2】:
            img = Image.open(images_dir +'/'+ filename)
            img.save(create_path +'/'+ filename.split('.')[0]+'.png', 'png')
    

    【讨论】:

    • 第一行打开图片(将filename替换为您的图片名称及其扩展名。第二行更改扩展名并将文件保存到同一目录
    • 我需要转换图片,不要重命名
    • img.save 就是这样做的。这不是强制性的,您可以使用create_path +'/'+ filename.split('.')[0]+'.png,您可以使用您喜欢的文件名将打开的文件保存为 png。
    猜你喜欢
    • 2018-12-29
    • 2011-01-18
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 2012-12-22
    • 2022-08-22
    相关资源
    最近更新 更多