在深度學習中遇到的opencv坑

圖像讀取

opencv 無法正確讀取用於語義分割的mask圖像, 因爲opencv在讀取png格式的圖像時, 自動將單通道轉換爲三通道, 像素值也發生改變

import cv2 as cv
import numpy as np
import PIL.Image as Image

def countColors(img):
    m, n = img.shape[:2]
    pxtype = list if img.ndim > 2 else int
    colors = []
    for i in range(m):
        for j in range(n):
            px = pxtype(img[i, j])
            if px in colors:
                continue
            else:
                colors.append(px)
    print(colors)

path = "examples/imgs/Person/2008_002176.png"

# 轉換的像素值
img = cv.imread(path)
print(img.shape)     # (294, 500, 3)
countColors(img)     # [[0, 0, 0], [0, 0, 128], [128, 0, 0], 
					 # [0, 128, 0], [0, 128, 128], [128, 0, 128]]

# 真實的像素值
img = np.array(Image.open(path))
print(img.shape)	 # (294, 500)
img = cv.merge([img, img, img])
countColors(img) 	 # [[0, 0, 0], [1, 1, 1], [4, 4, 4], 
					 # [2, 2, 2], [3, 3, 3], [5, 5, 5]]

# opencv單通道讀取
img = cv.imread(path, 0)
print(img.shape)	 # (294, 500)
img = cv.merge([img, img, img])
countColors(img)	 # [[0, 0, 0], [38, 38, 38], [14, 14, 14], 
					 # [75, 75, 75], [113, 113, 113], [52, 52, 52]]

可以看出, 原本的mask圖像是單通道的, 每個像素值代表了當前像素所屬的標籤. 當opencv轉換後, 是不存在這一概念的, 這樣讀入的數據是無法用於深度學習訓練的, 即使單通道讀入也是不一樣, 還很麻煩.

避坑指南: 使用 Pillow 庫讀取圖像


圖像尺寸變換

opencv的 cv::Size定義與Python版本中的shape定義是不一樣的.

Size相關的是 W x H

  • size = cv::Size(imageWidth, imageHeight)
  • img = cv.resize(img, (imageWidth, imageHeight))

shape相關的是 m x n

  • rows, cols = img.shape[:2]
  • imageHeight, imageWidth = img.shape[:2]

避坑指南:

imageHeight, imageWidth = img.shape[:2]
...  # processing
dst= cv.resize(dst, (imageWidth, imageHeight), interpolation=cv.INTER_CUBIC)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章