python - 灰度图像python实现
问题描述
我尝试使用 python 作为函数将 RGB 图像转换为灰度,但问题是我给它一个具有高度、宽度和通道的 RGB 图像,但是在代码之后我应该有一个只有高度和宽度的图像,但它给了我一个带有高度、宽度和通道的图像为什么?
def RGBtoGRAY(img):
height, width, channels = img.shape
grayimg = img
for i in range(height):
for j in range(width):
grayimg[i,j] = 0.3 * image[i,j][0] + 0.59 * image[i,j][1] + 0.11 * image[i,j][2]
return grayimg
输入图像的大小是
image.shape
(533, 541, 3)
输出图像的大小是
grayimage.shape
(533, 541, 3)
通常我想在输出图像的大小中找到
(533, 541)
解决方案
执行图像处理时应避免使用for
循环,因为它非常慢。相反,您可以使用针对向量操作进行了高度优化的 Numpy。使用这个灰度转换公式:
gray = R * .299 + G * .587 + B * .114
方法 #1: apply_along_axis
:
import cv2
import numpy as np
def grayscale(colors):
r, g, b = colors
return 0.299 * r + 0.587 * g + 0.114 * b
# Create image of size 100x100 of random pixels
# Convert to grayscale
image = np.random.randint(255, size=(100,100,3),dtype=np.uint8)
gray = np.apply_along_axis(grayscale, 2, image)
# Display
cv2.imshow('image', image)
cv2.imshow('gray', gray)
cv2.waitKey()
之前->
之后
方法#2: cv2.cvtColor
You could use OpenCV directly and read in the image as grayscale with cv2.imread
by passing in the cv2.IMREAD_GRAYSCALE
or 0
flag to load the image as grayscale.
image = cv2.imread('img.png', cv2.IMREAD_GRAYSCALE) # OR
# image = cv2.imread('img.png', 0)
If you already have the image loaded, you can convert the RGB or BGR image to grayscale using cv2.cvtColor
image = cv2.imread('img.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
推荐阅读
- haskell - 我想我找到了一个“不存在的单子”
- php - Codeigniter - 如何访问 result_array()
- python - 将带有列表和 dics 的 JSON 转换为数据框
- python - 带有“选择”的 BokehAPP 用于更改未显示其中一个图的图
- flutter - 使用 GestureDetector 的 onLongPressStart 每秒调整图标大小
- visual-foxpro - 如何检查项目/.exe 文件
- html - 如何实现标题和摄影师信用
- sas - 如何在 SAS 中对 Excel 文件进行不同的格式设置,例如粗体、斜体等?
- c# - 如何在紧凑模式下使用 MediaPlayerElement 移动窗口
- typescript - 如何指定排除已知继承索引键的类索引签名?