[英]How fast in Python change 3 channel rgb color image to 1 channel gray?
我在包含原始像素數據的 4D 數組中擁有近 40000 張圖像 - (示例數量、寬度、高度、通道)。 每個圖像的寬度為 32 像素,高度為 32 像素,以及 3 個 RGB 顏色通道。 我想將它們更改為灰度圖像(從 rgb 的 3 個通道獲得 1 的強度)。 我怎么能做得很快? 我的代碼:
import pickle
import cv2
training_file = "/train.p"
with open(training_file, mode='rb') as f:
train = pickle.load(f)
X_train = train['features']
def rgb2gray(rgb):
r, g, b = rgb[0], rgb[1], rgb[2]
gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
return gray
X_train_gray = X_train.copy()
for i in range (X_train_gray.shape[0]):
for j in range (X_train_gray.shape[1]):
for k in range (X_train_gray.shape[2]):
rgb = X_train_gray[i,j,k]
gray = rgb2gray(rgb)
X_train_gray[i,j,k] = gray
print("X_train image data shape =", X_train.shape)
print("X_train_grey image data shape =", X_train_gray.shape)
結果:
X_train_grey 圖像數據形狀 = (40000, 32, 32, 3)
X_train_grey 圖像數據形狀 = (40000, 32, 32, 1)
這很好,但需要很多時間。
我也嘗試使用 cv2:
X_train_gray = X_train[0].copy()
print("X_train_grey image data shape =", X_train_gray.shape)
X_train_gray = cv2.cvtColor(X_train_gray, cv2.COLOR_BGR2GRAY)
print("X_train_grey image data shape =", X_train_gray.shape)
結果:
X_train_grey 圖像數據形狀 = (32, 32, 3)
X_train_grey 圖像數據形狀 = (32, 32)
但我失去了強度,不知道如何獲得它。
那么如何快速將這些圖像從 3 通道 rgb 更改為 1 通道灰色?
如果你可以使用PIL。 應該沒問題。 我有 RGB 圖像並轉換它們:
from PIL import Image
img = Image.open("image_file_path") #for example image size : 28x28x3
img1 = img.convert('L') #convert a gray scale
print(img1.size)
>> (28,28)
但是圖片沒有頻道
y = np.expand_dims(img1, axis=-1)
print(y.shape)
>> (28,28,1)
我之前遇到過這個問題。這是最好的方法:您的代碼是正確的,但需要進行更多更改才能適用於灰度圖像。 這是代碼:
ii = cv2.imread("0.png")
gray_image = cv2.cvtColor(ii, cv2.COLOR_BGR2GRAY)
print(gray_image)
plt.imshow(gray_image,cmap='Greys')
plt.show()
這是結果:
[[196 196 197 195 195 194 195 197 196 195 194 194 196 194 196 189 188 195 195 196 197 198 195 49 19 195 19 19. . . [194 194 193 193 191 189 193 193 192 193 191 194 193 192 192 191 192 192 193 196 199 198 200 200 19] 200 200 19
嘗試使用:
cv::cvtColor(gray_img,color_img,CV_GRAY2BGR)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.