繁体   English   中英

如何将图像保存在 python 变量中,然后将其更改为灰度?

[英]how to save an image in python variable and then change it to grayscale?

我需要对条形码进行图像处理。 我知道我可以保存图片然后以灰度颜色模式加载它,但我不想加载图像,而是想将图像的颜色更改为灰度而不保存或没有其他图像。

imag=Image.open('barcode.png')
w, h = imag.size
region = imag.crop((0, 20, w, h-150))
region.save("regions.png")  #I dont want to save this image 
img=image.load_img("regions.png",color_mode="grayscale")  #I want to do this work in a variable i.e. changing the color of image into grayscale without having a need of loading an image

如果您可以使用 OpenCV,则 cv2.cvtColor 的工作方式如下:

import numpy as np
import cv2

img_filepath = "your_image.PNG"
img = cv2.imread(img_filepath)
grayed = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

cv2.imshow("grayed", grayed)
cv2.waitKey(0)
cv2.destroyAllWindows()

看起来你正在使用枕头。

在枕头里,你可以做Image.convert()

要转换为灰度,请执行Image.convert('LA')

模式LA是“8 位像素,黑白”和“阿尔法通道”的组合。 有关不同可用模式的更多信息,请参见此处


用以下代码替换您的代码:

imag = Image.open('barcode.png')
w, h = imag.size
region = imag.crop((0, 20, w, h-150))
img = region.convert('LA')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM