Search code examples
python-3.xopencvmatplotlibdicom

Vast difference in cv2 imshow vs matplotlib imshow?


I am currently working on a program that requires me to read DICOM files and display them correctly. After extracting the pixel array from the DICOM file, I ran it through both the imshow function from matplotlib and cv2. To my surprise they both yield vastly different images. One has color while the other has no, and one shows more detail than the other. Im confused as to why this is happening. I found Difference between plt.show and cv2.imshow? and tried converting the pixels to BRG instead of RGB what cv2 uses but this changes nothing. I am wondering why it is that these 2 frameworks show the same pixel buffer so differently. below is my code and an image to show the outcomes

import cv2
import os
import pydicom
import numpy as np
import matplotlib.pyplot as plt
inputdir = 'datasets/dicom/98890234/20030505/CT/CT2/'
outdir = 'datasets/dicom/pngs/'

test_list = [ f for f in  os.listdir(inputdir)]
for f in test_list[:1]:   # remove "[:10]" to convert all images 
    ds = pydicom.dcmread(inputdir + f)
    img = np.array(ds.pixel_array, dtype = np.uint8)  # get image array
    rows,cols = img.shape    
    cannyImg = cv2.Canny(img, cols, rows)
    cv2.imshow('thing',cv2.cvtColor(img, cv2.COLOR_BRG2RBG))
    cv2.imshow('thingCanny', cannyImg)
    plt.imshow(ds.pixel_array)
    plt.show()
    cv2.waitKey()

enter image description here


Solution

  • Not an answer but too long for a comment. I think the root cause of your problems is in the initialization of the array already:

    img = np.array(ds.pixel_array, dtype = np.uint8)
    

    uint8 is presumably not what you have in the DICOM file. First because it looks like a CT image which is usually stored with 10+ bpp and second because the artifacts you are facing look very familiar to me. These kind of artifacts (dense bones displayed in black, gradient effects) usually occur if >8 bit pixeldata is interpreted as 8bit.

    BTW: To me, both renderings look obviously incorrect.

    Sorry for not being a python expert and just being able to tell what is wrong but unable to tell how to get it right.