简体   繁体   English

如何将灰度图像变成RGB?

[英]How to turn grayscale image into RGB?

I am making a application in python that allows people to share their screens, but in order to get a decent frame rate I wanted to compress the image into a grayscale format and then on the client side turn it back into an RGB image.我正在 python 中制作一个应用程序,允许人们共享他们的屏幕,但为了获得合适的帧速率,我想将图像压缩为灰度格式,然后在客户端将其转换回 RGB 图像。 But when I tried to do that it still showed a grayscale image.但是当我尝试这样做时,它仍然显示灰度图像。

Then I tried using HSV color conversion which did display the color, but with a red filter for some reason.然后我尝试使用 HSV 颜色转换,它确实显示了颜色,但出于某种原因使用了红色滤镜。

I won't show all of the code due to the fact it is at least 2000 lines, but I will show what part of the code where I am having my problem.我不会显示所有代码,因为它至少有 2000 行,但我会显示我遇到问题的代码部分。

Server side:服务器端:

sct_img = sct.grab(bounding_box)
img_np = np.array(sct_img)
frame = img_np
frame = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
frame = cv2.resize(frame, (0,0), fx = 0.70, fy = 0.70)
data = pickle.dumps(frame)
message_size = struct.pack("L", len(data))
clientsocket.sendall(message_size + data)

Client side:客户端:

 frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2BGR)
 frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
 frame = cv2.resize(frame, (x, y))
 cv2.imshow('frame', frame)

When you convert an RGB image to grayscale, color data gets thrown away, hence you won't be able to get the original image back.当您将 RGB 图像转换为灰度图像时,颜色数据会被丢弃,因此您将无法恢复原始图像。 Observe the output from code below:观察以下代码中的 output:

import cv2
import numpy as np

# Create image
img = np.full((500, 500, 3), 255, 'uint8')
cv2.rectangle(img, (50, 100), (250, 300), (0, 0, 96), -1)
cv2.circle(img, (300, 350), 100, (0, 50, 0), -1)
cv2.drawContours(img, [np.array([(300, 50), (200, 250), (400, 250)])], 0, (255, 0, 0), -1)

# Convert to grayscale
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(np.unique(img_gray))

# Show images
cv2.imshow("BGR", img)
cv2.imshow("Gray", img_gray)
cv2.waitKey(0)

Output: Output:

在此处输入图像描述

在此处输入图像描述

As you can see, with the image of a red, green and blue shape (each a specific shade of its color) , converting it into grayscale results in the three colors turning into one;如您所见,对于红色、绿色和蓝色形状的图像(每种颜色都有特定的阴影) ,将其转换为灰度会导致三个 colors 变成一个; (29, 29, 29) . (29, 29, 29) There is no way the computer will be able to tell that the three shapes used to be different colors.计算机无法判断这三个形状过去是不同的 colors。

When you reduce a color image to grayscale, you're discarding information.当您将彩色图像缩小为灰度时,您正在丢弃信息。 There's no way to get color back.没有办法恢复颜色。 If you want to get an acceptable frame rate, you're going to have to choose some other approach.如果您想获得可接受的帧速率,您将不得不选择其他方法。

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

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