在python / django中使用灰度的最佳方法是什么?

时间:2015-07-28 20:32:22

标签: python django image imagemagick opencv3.0

我想将我的图片灰度图片上传到django。所以我找到了两种方法,opencv或imagemagick。在imagemagick中,imagemagickWand可能会更好,因为它会减少。

从教程中我认为openCV更容易实现。

有什么想法吗?

2 个答案:

答案 0 :(得分:4)

如果先转换为线性光,则可以获得更好的效果。

sRGB图像将具有大约2.4的伽玛值,也就是说,明亮区域中的范围比黑暗更大。如果您对sRGB图像执行0.2 r + 0.7 g + 0.1 b,则可能会破坏亮度关系,例如:

enter image description here

从左侧开始,这些是原始图像,由sRGB的简单重组制成的灰度,由非常奇特的非局部自适应算法制作的灰度,以及由线性光制成的灰度。线性光版本保持红蓝差异优于非线性,但它看起来不像自适应版本那么好。你可以read about the adaptive algorithm here

如果你确定你有sRGB,或者更好的是,使用ICC配置文件转换为XYZ,可以通过简单的ungamma转换为线性光。 pyvips内置了线性浅灰度转换,请尝试:

import pyvips

image = pyvips.Image.new_from_file("/home/john/pics/k2.jpg", access="sequential") 
image = image.colourspace("b-w")
image.write_to_file("x.jpg")

假设您有sRGB源。如果要通过嵌入的配置文件导入,请尝试:

import pyvips

image = pyvips.Image.new_from_file("/home/john/pics/k2.jpg", access="sequential")

try:
    # import with an embedded profile, if possible
    # import to XYZ PCS (linear light)
    image = image.icc_import(embedded = True, pcs = "xyz")
except:
    # no or broken profile, fall back to the default sRGB 
    # interpretation
    pass

image = image.colourspace("b-w")
image.write_to_file("x.jpg")

vips的优势在于质量更高,faster, and much lower memory use。对于10,000 x 10,000像素RGB JPEG,我看到:

$ time ./magickwand.py 
real    0m2.613s
user    0m2.084s
sys 0m0.500s
peak RES 840MB
$ time ./vips.py
real    0m1.722s
user    0m5.716s
sys 0m0.116s
peak RES 54MB

这是在双核笔记本电脑上。

答案 1 :(得分:1)

  

在python / django中使用灰度的最佳方法是什么?

选择。

ImageMagick的魔杖库

from wand.image import Image
with Image(filename='logo:') as img:
    img.colorspace = 'gray'
    img.save(filename='logo_gray.jpg')

或CV2

import cv2
img = cv2.imread('example.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imwrite('example_gray.jpg',gray)

这两个项目都是成熟,稳定,并拥有庞大的社区基础。尝试安装这两个库,然后进行试验。

最后灰度是(来自wikipedia)。

Y = 0.2126 * RED + 0.7152 * GREEN + 0.0722 * BLUE

两者都做得很好,并依赖代表(即libjpeg)阅读&写图像格式。