我正在嘗試向圖像添加第4個「頻道」。具體來說,我有一個RGB圖像,並希望將Canny濾波器找到的邊緣檢測圖像添加到該圖像矩陣中,然後將其用作神經網絡的輸入。向圖像添加新頻道
我有邊緣檢測工作,我甚至可以追加圖像,但由於某種原因,循環後數據'恢復'。我對圖像大小所做的更改不會保留。
代碼
我有三套32x32x3
彩色圖像:X_train
,X_valid
和X_test
。對於每一個,我正常化圖像,然後添加漸變。追加似乎在循環時產生影響,但循環後變更不存在。
代碼片斷
import cv2 as cv
example_record = 2
print('X_train is shape {}'.format(X_train.shape))
print('X_valid is shape {}'.format(X_valid.shape))
print('X_test is shape {}'.format(X_test.shape))
# Show before
plt.imshow(X_valid[example_record])
plt.title('Validation Input {} Before Normalization'.format(example_record))
# Normalize
canny_low = 50
canny_high = 100
for dataset in [X_train, X_valid, X_test]:
for i, img in enumerate(dataset):
cv.normalize(img, img, 0, 255, cv.NORM_MINMAX)
edges = cv.Canny(img, canny_low, canny_high)
edges = np.reshape(edges, (img.shape[0], img.shape[1], 1))
img = np.concatenate((img, edges),axis=2)
if i == 0:
print('img shape after concatenation {}'.format(img.shape))
# Show after
plt.figure()
print('Updated image shape: {}'.format(X_valid[example_record].shape))
plt.imshow(X_valid[example_record])
plt.title('Validation Input {} After Normalization'.format(example_record))
輸出
X_train is shape (34799, 32, 32, 3)
X_valid is shape (4410, 32, 32, 3)
X_test is shape (12630, 32, 32, 3)
img shape after concatenation (32, 32, 4)
img shape after concatenation (32, 32, 4)
img shape after concatenation (32, 32, 4)
Updated image shape: (32, 32, 3)
其他企圖
如果我更換img = np.concatenate((img, edges),axis=2)
與dataset[i] = np.concatenate((img, edges),axis=2)
,我得到的錯誤:
21 edges = cv.Canny(img, canny_low, canny_high)
22 edges = np.reshape(edges, (img.shape[0], img.shape[1], 1))
---> 23 dataset[i] = np.concatenate((img, edges),axis=2)
24 if i == 0:
25 print('img shape after concatenation {}'.format(img.shape))
ValueError: could not broadcast input array from shape (32,32,4) into shape (32,32,3)
我強烈建議將img寫入新列表。 –