def time_rgb_ybr_large(self): """Time converting RGB to YBR.""" for ii in range(1): convert_color_space(self.arr_large, "RGB", "YBR_FULL", per_frame=True)
def test_rgb_ybr_rgb_single_frame(self): """Test round trip conversion of single framed pixel data.""" ds = dcmread(RGB_8_3_1F) arr = ds.pixel_array assert (255, 0, 0) == tuple(arr[5, 50, :]) assert (255, 128, 128) == tuple(arr[15, 50, :]) assert (0, 255, 0) == tuple(arr[25, 50, :]) assert (128, 255, 128) == tuple(arr[35, 50, :]) assert (0, 0, 255) == tuple(arr[45, 50, :]) assert (128, 128, 255) == tuple(arr[55, 50, :]) assert (0, 0, 0) == tuple(arr[65, 50, :]) assert (64, 64, 64) == tuple(arr[75, 50, :]) assert (192, 192, 192) == tuple(arr[85, 50, :]) assert (255, 255, 255) == tuple(arr[95, 50, :]) ybr = convert_color_space(arr, 'RGB', 'YBR_FULL') assert (76, 85, 255) == tuple(ybr[5, 50, :]) assert (166, 107, 192) == tuple(ybr[15, 50, :]) assert (150, 44, 21) == tuple(ybr[25, 50, :]) assert (203, 86, 75) == tuple(ybr[35, 50, :]) assert (29, 255, 107) == tuple(ybr[45, 50, :]) assert (142, 192, 118) == tuple(ybr[55, 50, :]) assert (0, 128, 128) == tuple(ybr[65, 50, :]) assert (64, 128, 128) == tuple(ybr[75, 50, :]) assert (192, 128, 128) == tuple(ybr[85, 50, :]) assert (255, 128, 128) == tuple(ybr[95, 50, :]) # Round trip -> rounding errors get compounded rgb = convert_color_space(ybr, 'YBR_FULL', 'RGB') # All pixels within +/- 1 units assert np.allclose(rgb, arr, atol=1) assert rgb.shape == arr.shape
def test_dataset_pixel_array_handler_needs_convert(self): """Test Dataset.pixel_array when converting to RGB.""" ds = dcmread(EXPL_8_3_1F) # Convert to YBR first arr = ds.pixel_array assert (255, 0, 0) == tuple(arr[5, 50, :]) arr = convert_color_space(arr, 'RGB', 'YBR_FULL') ds.PixelData = arr.tobytes() del ds._pixel_array # Weird PyPy2 issue without this # Test normal functioning (False) assert (76, 85, 255) == tuple(ds.pixel_array[5, 50, :]) def needs_convert(ds): """Change the default return to True""" return True # Test modified orig_fn = NP_HANDLER.needs_to_convert_to_RGB NP_HANDLER.needs_to_convert_to_RGB = needs_convert # Ensure the pixel array gets updated ds._pixel_id = None assert (254, 0, 0) == tuple(ds.pixel_array[5, 50, :]) # Reset NP_HANDLER.needs_to_convert_to_RGB = orig_fn
def test_3s_1f_ybr_444_non(self): """Test YBR with 444 subsampling.""" # +cy is YCbCr # +s4 is 444 subsampling w/ YBR_FULL - DICOM non-conformant ds = self.ds['SC_rgb_dcmtk_+eb+cy+s4.dcm']['ds'] assert self.uid == ds.file_meta.TransferSyntaxUID assert 3 == ds.SamplesPerPixel assert 1 == getattr(ds, 'NumberOfFrames', 1) assert 'YBR_FULL' == ds.PhotometricInterpretation assert 8 == ds.BitsAllocated == ds.BitsStored assert 0 == ds.PixelRepresentation arr = ds.pixel_array assert arr.flags.writeable assert 'uint8' == arr.dtype assert (ds.Rows, ds.Columns, 3) == arr.shape arr = convert_color_space(arr, 'YBR_FULL', 'RGB') #self.plot(arr) assert (254, 0, 0) == tuple(arr[5, 50, :]) assert (255, 127, 127) == tuple(arr[15, 50, :]) assert (0, 255, 5) == tuple(arr[25, 50, :]) assert (129, 255, 129) == tuple(arr[35, 50, :]) assert (0, 0, 254) == tuple(arr[45, 50, :]) assert (128, 127, 255) == tuple(arr[55, 50, :]) assert (0, 0, 0) == tuple(arr[65, 50, :]) assert (64, 64, 64) == tuple(arr[75, 50, :]) assert (192, 192, 192) == tuple(arr[85, 50, :]) assert (255, 255, 255) == tuple(arr[95, 50, :])
def test_3s_Nf_ybr_422(self): """Test 3 sample/px with N frames.""" ds = self.ds['color3d_jpeg_baseline.dcm']['ds'] assert self.uid == ds.file_meta.TransferSyntaxUID assert 3 == ds.SamplesPerPixel assert 1 != getattr(ds, 'NumberOfFrames', 1) assert 8 == ds.BitsAllocated == ds.BitsStored assert 'YBR_FULL_422' == ds.PhotometricInterpretation assert 0 == ds.PixelRepresentation arr = ds.pixel_array assert arr.flags.writeable assert 'uint8' == arr.dtype assert (ds.NumberOfFrames, ds.Rows, ds.Columns, 3) == arr.shape # Gives a MemoryError in GitHub CI build otherwise arr = arr[0:10, ...] arr = convert_color_space(arr, 'YBR_FULL', 'RGB') #self.plot(arr, index=3) # GDCM: all match assert (41, 41, 41) == tuple(arr[3, 159, 290, :]) assert (57, 57, 57) == tuple(arr[3, 169, 290, :]) # Pillow: assert (71, 168, 125) == tuple(arr[3, 41, 380, :]) assert (72, 167, 125) == tuple(arr[3, 41, 380, :])
def test_rgb_ybr_rgb_multi_frame(self): """Test round trip conversion of multi-framed pixel data.""" ds = dcmread(RGB_8_3_2F) arr = ds.pixel_array assert (255, 0, 0) == tuple(arr[0, 5, 50, :]) assert (255, 128, 128) == tuple(arr[0, 15, 50, :]) assert (0, 255, 0) == tuple(arr[0, 25, 50, :]) assert (128, 255, 128) == tuple(arr[0, 35, 50, :]) assert (0, 0, 255) == tuple(arr[0, 45, 50, :]) assert (128, 128, 255) == tuple(arr[0, 55, 50, :]) assert (0, 0, 0) == tuple(arr[0, 65, 50, :]) assert (64, 64, 64) == tuple(arr[0, 75, 50, :]) assert (192, 192, 192) == tuple(arr[0, 85, 50, :]) assert (255, 255, 255) == tuple(arr[0, 95, 50, :]) # Frame 2 is frame 1 inverted assert np.array_equal((2**ds.BitsAllocated - 1) - arr[1], arr[0]) ybr = convert_color_space(arr, 'RGB', 'YBR_FULL') assert (76, 85, 255) == tuple(ybr[0, 5, 50, :]) assert (166, 107, 192) == tuple(ybr[0, 15, 50, :]) assert (150, 44, 21) == tuple(ybr[0, 25, 50, :]) assert (203, 86, 75) == tuple(ybr[0, 35, 50, :]) assert (29, 255, 107) == tuple(ybr[0, 45, 50, :]) assert (142, 192, 118) == tuple(ybr[0, 55, 50, :]) assert (0, 128, 128) == tuple(ybr[0, 65, 50, :]) assert (64, 128, 128) == tuple(ybr[0, 75, 50, :]) assert (192, 128, 128) == tuple(ybr[0, 85, 50, :]) assert (255, 128, 128) == tuple(ybr[0, 95, 50, :]) # Frame 2 assert (179, 171, 1) == tuple(ybr[1, 5, 50, :]) assert (89, 149, 65) == tuple(ybr[1, 15, 50, :]) assert (105, 212, 235) == tuple(ybr[1, 25, 50, :]) assert (52, 170, 181) == tuple(ybr[1, 35, 50, :]) assert (226, 1, 149) == tuple(ybr[1, 45, 50, :]) assert (113, 65, 138) == tuple(ybr[1, 55, 50, :]) assert (255, 128, 128) == tuple(ybr[1, 65, 50, :]) assert (191, 128, 128) == tuple(ybr[1, 75, 50, :]) assert (63, 128, 128) == tuple(ybr[1, 85, 50, :]) assert (0, 128, 128) == tuple(ybr[1, 95, 50, :]) # Round trip -> rounding errors get compounded rgb = convert_color_space(ybr, 'YBR_FULL', 'RGB') # All pixels within +/- 1 units assert np.allclose(rgb, arr, atol=1) assert rgb.shape == arr.shape
def test_array(self, fpath, rpath, fixes): """Test pixel_array returns correct values.""" ds = dcmread(fpath) # May need to correct some element values for kw, val in fixes.items(): setattr(ds, kw, val) arr = ds.pixel_array if 'YBR_FULL' in ds.PhotometricInterpretation: arr = convert_color_space(arr, ds.PhotometricInterpretation, 'RGB') ref = dcmread(rpath).pixel_array assert np.array_equal(arr, ref)
def test_rgb_ybr_rgb_single_frame(self): """Test round trip conversion of single framed pixel data.""" ds = dcmread(RGB_8_3_1F) arr = ds.pixel_array assert (255, 0, 0) == tuple(arr[5, 50, :]) assert (255, 128, 128) == tuple(arr[15, 50, :]) assert (0, 255, 0) == tuple(arr[25, 50, :]) assert (128, 255, 128) == tuple(arr[35, 50, :]) assert (0, 0, 255) == tuple(arr[45, 50, :]) assert (128, 128, 255) == tuple(arr[55, 50, :]) assert (0, 0, 0) == tuple(arr[65, 50, :]) assert (64, 64, 64) == tuple(arr[75, 50, :]) assert (192, 192, 192) == tuple(arr[85, 50, :]) assert (255, 255, 255) == tuple(arr[95, 50, :]) ybr = convert_color_space(arr, 'RGB', 'YBR_FULL') assert (76, 85, 255) == tuple(ybr[5, 50, :]) assert (166, 107, 192) == tuple(ybr[15, 50, :]) assert (150, 44, 21) == tuple(ybr[25, 50, :]) assert (203, 86, 75) == tuple(ybr[35, 50, :]) assert (29, 255, 107) == tuple(ybr[45, 50, :]) assert (142, 192, 118) == tuple(ybr[55, 50, :]) assert (0, 128, 128) == tuple(ybr[65, 50, :]) assert (64, 128, 128) == tuple(ybr[75, 50, :]) assert (192, 128, 128) == tuple(ybr[85, 50, :]) assert (255, 128, 128) == tuple(ybr[95, 50, :]) # Round trip -> rounding errors get compounded rgb = convert_color_space(ybr, 'YBR_FULL', 'RGB') assert (254, 0, 0) == tuple(rgb[5, 50, :]) assert (255, 128, 129) == tuple(rgb[15, 50, :]) assert (0, 255, 1) == tuple(rgb[25, 50, :]) assert (129, 255, 129) == tuple(rgb[35, 50, :]) assert (0, 0, 254) == tuple(rgb[45, 50, :]) assert (128, 127, 255) == tuple(rgb[55, 50, :]) assert (0, 0, 0) == tuple(rgb[65, 50, :]) assert (64, 64, 64) == tuple(rgb[75, 50, :]) assert (192, 192, 192) == tuple(rgb[85, 50, :]) assert (255, 255, 255) == tuple(rgb[95, 50, :])
def test_color_3d(self): """Test decoding JPEG with pillow handler succeeds.""" ds = dcmread(JPGB_08_08_3_0_120F_YBR_FULL_422) assert "YBR_FULL_422" == ds.PhotometricInterpretation arr = ds.pixel_array assert arr.flags.writeable assert (120, 480, 640, 3) == arr.shape arr = convert_color_space(arr, 'YBR_FULL_422', 'RGB') # this test points were manually identified in Osirix viewer assert (41, 41, 41) == tuple(arr[3, 159, 290, :]) assert (57, 57, 57) == tuple(arr[3, 169, 290, :]) assert "YBR_FULL_422" == ds.PhotometricInterpretation
def extract_images_from_dicom(dicom_obj): pixel_array = dicom_obj.pixel_array interpretation_str = str(getattr(dicom_obj, 'PhotometricInterpretation', None)) if interpretation_str in ('YBR_FULL_422', 'YBR_FULL'): pixel_array = convert_color_space(pixel_array, interpretation_str, 'RGB') dcm_channels = pixel_array.shape images = [] if (len(dcm_channels) > 3 and dcm_channels[-1] == 3) or (len(dcm_channels) == 3 and dcm_channels[-1] != 3): for i in range(dcm_channels[0]): images.append(prepare_dicom_image(pixel_array[i], dicom_obj)) else: images.append(prepare_dicom_image(pixel_array, dicom_obj)) return images
def test_generate_frames(self, fpath, rpath, val, tol): """Test pixel_array returns correct values.""" ds = dcmread(fpath) frame_generator = generate_frames(ds) ref = dcmread(rpath).pixel_array nr_frames = getattr(ds, 'NumberOfFrames', 1) for ii in range(nr_frames): arr = next(frame_generator) if 'YBR' in ds.PhotometricInterpretation: arr = convert_color_space(arr, ds.PhotometricInterpretation, 'RGB') if nr_frames > 1: assert np.allclose(arr, ref[ii, ...], atol=tol) else: assert np.allclose(arr, ref, atol=tol) with pytest.raises(StopIteration): next(frame_generator)
def get_pixels(dicom_file): pixels = dicom_file.pixel_array if dicom_file.PhotometricInterpretation == 'PALETTE COLOR': pixels = apply_color_lut(pixels, dicom_file) elif dicom_file.PhotometricInterpretation == 'YBR_FULL_422' or dicom_file.PhotometricInterpretation == 'YBR_FULL': pixels = convert_color_space(pixels, dicom_file.PhotometricInterpretation, 'RGB') dicom_file.PhotometricInterpretation = 'RGB' elif len(pixels.shape) == 2 and (dicom_file.PhotometricInterpretation == 'MONOCHROME1' or dicom_file.PhotometricInterpretation == 'MONOCHROME2'): pixels = np.stack((pixels, pixels, pixels), axis=2) # handle different dtypes if pixels.dtype == np.uint16: pixels = (pixels * (256.0 / pixels.max())).astype(np.uint8) elif pixels.dtype == np.int16: pix_max = pixels.max() pix_min = pixels.min() pixels = ((pixels + pix_min) * (256.0 / (pix_max - pix_min))).astype(np.uint8) return pixels
def test_array(self, fpath, rpath, values): """Test pixel_array returns correct values.""" ds = dcmread(fpath) arr = ds.pixel_array if 'YBR' in ds.PhotometricInterpretation: arr = convert_color_space(arr, ds.PhotometricInterpretation, 'RGB') ref = dcmread(rpath).pixel_array if values: assert tuple(arr[5, 50, :]) == values[0] assert tuple(arr[15, 50, :]) == values[1] assert tuple(arr[25, 50, :]) == values[2] assert tuple(arr[35, 50, :]) == values[3] assert tuple(arr[45, 50, :]) == values[4] assert tuple(arr[55, 50, :]) == values[5] assert tuple(arr[65, 50, :]) == values[6] assert tuple(arr[75, 50, :]) == values[7] assert tuple(arr[85, 50, :]) == values[8] assert tuple(arr[95, 50, :]) == values[9] assert np.array_equal(arr, ref)
def test_array(self, fpath, rpath, val, tol): """Test pixel_array returns correct values.""" ds = dcmread(fpath) arr = ds.pixel_array if 'YBR' in ds.PhotometricInterpretation: arr = convert_color_space(arr, ds.PhotometricInterpretation, 'RGB') ref = dcmread(rpath).pixel_array if val: assert tuple(arr[5, 50, :]) == val[0] assert tuple(arr[15, 50, :]) == val[1] assert tuple(arr[25, 50, :]) == val[2] assert tuple(arr[35, 50, :]) == val[3] assert tuple(arr[45, 50, :]) == val[4] assert tuple(arr[55, 50, :]) == val[5] assert tuple(arr[65, 50, :]) == val[6] assert tuple(arr[75, 50, :]) == val[7] assert tuple(arr[85, 50, :]) == val[8] assert tuple(arr[95, 50, :]) == val[9] # All results within `tol` intensity units of the reference assert np.allclose(arr, ref, atol=tol)
def __iter__(self): if self._length == 1: self._pixel_array = np.expand_dims(self._pixel_array, axis=0) for pixel_array in self._pixel_array: # Normalization to an output range 0..255, 0..65535 pixel_array = pixel_array - self._min_value pixel_array = pixel_array.astype(int) * (2**self._depth - 1) pixel_array = pixel_array // (self._max_value - self._min_value) # In some cases we need to convert colors additionally if 'YBR' in self._photometric_interpretation: pixel_array = convert_color_space( pixel_array, self._photometric_interpretation, 'RGB') if self._depth == 8: image = Image.fromarray(pixel_array.astype(np.uint8)) elif self._depth == 16: image = Image.fromarray(pixel_array.astype(np.uint16)) else: raise Exception('Not supported depth {}'.format(self._depth)) yield image
def test_convert_color_space_raises(self): """Test that convert_color_space raises exception.""" with pytest.raises(ImportError, match="Numpy is required to convert"): convert_color_space(None, None, None)
def test_unknown_current_raises(self): """Test an unknown current color space raises exception.""" with pytest.raises(NotImplementedError, match="Conversion from TEST to RGB is not suppo"): convert_color_space(None, 'TEST', 'RGB')
def test_unknown_desired_raises(self): """Test an unknown desdired color space raises exception.""" with pytest.raises(NotImplementedError, match="Conversion from RGB to TEST is not suppo"): convert_color_space(None, 'RGB', 'TEST')
def test_current_is_desired(self): """Test that the array is unchanged when current matches desired.""" arr = np.ones((2, 3)) assert np.array_equal(arr, convert_color_space(arr, 'RGB', 'RGB'))
def time_ybr_rgb(self): """Time converting from YBR to RGB color space.""" for ii in range(self.no_runs): convert_color_space(self.ybr_full, 'YBR_FULL', 'RGB')
def time_rgb_ybr(self): """Time converting from RGB to YBR color space.""" for ii in range(self.no_runs): convert_color_space(self.rgb, 'RGB', 'YBR_FULL')
def test_rgb_ybr_rgb_multi_frame(self): """Test round trip conversion of multi-framed pixel data.""" ds = dcmread(RGB_8_3_2F) arr = ds.pixel_array assert (255, 0, 0) == tuple(arr[0, 5, 50, :]) assert (255, 128, 128) == tuple(arr[0, 15, 50, :]) assert (0, 255, 0) == tuple(arr[0, 25, 50, :]) assert (128, 255, 128) == tuple(arr[0, 35, 50, :]) assert (0, 0, 255) == tuple(arr[0, 45, 50, :]) assert (128, 128, 255) == tuple(arr[0, 55, 50, :]) assert (0, 0, 0) == tuple(arr[0, 65, 50, :]) assert (64, 64, 64) == tuple(arr[0, 75, 50, :]) assert (192, 192, 192) == tuple(arr[0, 85, 50, :]) assert (255, 255, 255) == tuple(arr[0, 95, 50, :]) # Frame 2 is frame 1 inverted assert np.array_equal((2**ds.BitsAllocated - 1) - arr[1], arr[0]) ybr = convert_color_space(arr, 'RGB', 'YBR_FULL') assert (76, 85, 255) == tuple(ybr[0, 5, 50, :]) assert (166, 107, 192) == tuple(ybr[0, 15, 50, :]) assert (150, 44, 21) == tuple(ybr[0, 25, 50, :]) assert (203, 86, 75) == tuple(ybr[0, 35, 50, :]) assert (29, 255, 107) == tuple(ybr[0, 45, 50, :]) assert (142, 192, 118) == tuple(ybr[0, 55, 50, :]) assert (0, 128, 128) == tuple(ybr[0, 65, 50, :]) assert (64, 128, 128) == tuple(ybr[0, 75, 50, :]) assert (192, 128, 128) == tuple(ybr[0, 85, 50, :]) assert (255, 128, 128) == tuple(ybr[0, 95, 50, :]) # Frame 2 assert (179, 171, 1) == tuple(ybr[1, 5, 50, :]) assert (89, 149, 65) == tuple(ybr[1, 15, 50, :]) assert (105, 212, 235) == tuple(ybr[1, 25, 50, :]) assert (52, 170, 181) == tuple(ybr[1, 35, 50, :]) assert (226, 1, 149) == tuple(ybr[1, 45, 50, :]) assert (113, 65, 138) == tuple(ybr[1, 55, 50, :]) assert (255, 128, 128) == tuple(ybr[1, 65, 50, :]) assert (191, 128, 128) == tuple(ybr[1, 75, 50, :]) assert (63, 128, 128) == tuple(ybr[1, 85, 50, :]) assert (0, 128, 128) == tuple(ybr[1, 95, 50, :]) # Round trip -> rounding errors get compounded rgb = convert_color_space(ybr, 'YBR_FULL', 'RGB') assert (254, 0, 0) == tuple(rgb[0, 5, 50, :]) assert (255, 128, 129) == tuple(rgb[0, 15, 50, :]) assert (0, 255, 1) == tuple(rgb[0, 25, 50, :]) assert (129, 255, 129) == tuple(rgb[0, 35, 50, :]) assert (0, 0, 254) == tuple(rgb[0, 45, 50, :]) assert (128, 127, 255) == tuple(rgb[0, 55, 50, :]) assert (0, 0, 0) == tuple(rgb[0, 65, 50, :]) assert (64, 64, 64) == tuple(rgb[0, 75, 50, :]) assert (192, 192, 192) == tuple(rgb[0, 85, 50, :]) assert (255, 255, 255) == tuple(rgb[0, 95, 50, :]) # Frame 2 assert (1, 255, 255) == tuple(rgb[1, 5, 50, :]) assert (1, 127, 126) == tuple(rgb[1, 15, 50, :]) assert (255, 0, 254) == tuple(rgb[1, 25, 50, :]) assert (126, 0, 126) == tuple(rgb[1, 35, 50, :]) assert (255, 255, 1) == tuple(rgb[1, 45, 50, :]) assert (127, 128, 1) == tuple(rgb[1, 55, 50, :]) assert (255, 255, 255) == tuple(rgb[1, 65, 50, :]) assert (191, 191, 191) == tuple(rgb[1, 75, 50, :]) assert (63, 63, 63) == tuple(rgb[1, 85, 50, :]) assert (0, 0, 0) == tuple(rgb[1, 95, 50, :])
def process(filelist, outputlist, isMultiprocessing=True, p_no=1, isOnlyUSImage=False): print("isMultiprocessing:", isMultiprocessing) for serial_no, filepath in enumerate(filelist): try: ds = dicom.dcmread(filepath) except InvalidDicomError as e: print("Error:", e) # try: # ds[0x00081080].value # except KeyError as e: # print("Error:", e) # continue try: pixel_array = ds.pixel_array except Exception: with open("Error.txt", "a") as f: f.write(filepath) continue print(filepath) photometricInterpretation = ds[0x00280004].value if photometricInterpretation == "YBR_FULL_422": pixel_array = convert_color_space(pixel_array, current="YBR_FULL_422", desired="RGB") elif photometricInterpretation == "YBR_FULL": pixel_array = convert_color_space(pixel_array, current="YBR_FULL", desired="RGB") elif photometricInterpretation == "PALETTE COLOR": img = [] for i in range(pixel_array.shape[0]): img.append(apply_color_lut(pixel_array[i], ds)) pixel_array = np.array(img) if pixel_array.ndim == 4: # if the data is video # Get some information print(pixel_array.shape) filename = filepath.split("\\")[-1] focus_depth = -1 if 0x00185012 in ds: focus_depth = ds[0x00185012].value if isOnlyUSImage: us_sequence = ds[0x00186011][0] x0_region = us_sequence[0x00186018].value y0_region = us_sequence[0x0018601a].value x1_region = us_sequence[0x0018601c].value y1_region = us_sequence[0x0018601e].value pixel_array = pixel_array[:, y0_region:y1_region, x0_region:x1_region, :] # x0_offset = 35 # x1_offset = 795 # pixel_array = pixel_array[:, : , x0_offset : x1_offset, :] if isMultiprocessing: p_list = [] for i in range(p_no): p_list.append( mp.Process( target=removeWhiteNoisesAndSave, args=(pixel_array[int(i * len(pixel_array) / p_no):int( (i + 1) * len(pixel_array) / p_no)], filename, focus_depth, int(i * len(pixel_array) / p_no), outputlist[serial_no]))) for i in range(p_no): p_list[i].start() for i in range(p_no): p_list[i].join() else: removeWhiteNoisesAndSave(pixel_array, filename, focus_depth, 0, outputlist[serial_no]) else: for i in range(pixel_array.shape[0]): outputpath = os.path.join( outputlist[serial_no], filename.split(".")[0] + "_" + str(focus_depth) + "_Frame" + str(i) + ".png") cv2.imwrite( outputpath, cv2.cvtColor(pixel_array[i], cv2.COLOR_RGB2BGR)) elif pixel_array.ndim == 3: # if the data is picture print(pixel_array.shape) filename = filepath.split("\\")[-1] focus_depth = -1 if 0x00185012 in ds: focus_depth = ds[0x00185012].value if isOnlyUSImage: us_sequence = ds[0x00186011][0] x0_region = us_sequence[0x00186018].value y0_region = us_sequence[0x0018601a].value x1_region = us_sequence[0x0018601c].value y1_region = us_sequence[0x0018601e].value pixel_array = pixel_array[:, y0_region:y1_region, x0_region:x1_region, :] # x0_offset = 35 # x1_offset = 795 # pixel_array = pixel_array[:, x0_offset : x1_offset, :] removeWhiteNoisesAndSave(pixel_array, filename, focus_depth, 0, outputlist[serial_no]) else: outputpath = os.path.join( outputlist[serial_no], filename.split(".")[0] + "_" + str(focus_depth) + "_Frame0.png") cv2.imwrite(outputpath, cv2.cvtColor(pixel_array, cv2.COLOR_RGB2BGR)) elif pixel_array.ndim == 2: # if the data is picture and in grayscale print(pixel_array.shape) filename = filepath.split("\\")[-1] outputpath = os.path.join(outputlist[serial_no], filename.split(".")[0] + ".png") cv2.imwrite(outputpath, pixel_array) open("state.txt", "w").write("0")
import cv2 import os import pydicom from pydicom.pixel_data_handlers.util import convert_color_space inputdir = 'C:/Users/kimdh/PycharmProjects/data/USdicom_ex/' outdir = 'C:/Users/kimdh/PycharmProjects/data/dicom_convert_to_png/' test_list = [f for f in os.listdir(inputdir)] for f in test_list: ds = pydicom.dcmread(inputdir + f) # read dicom image temp = ds.pixel_array # get image array img = convert_color_space(temp, 'YBR_FULL', 'RGB') cv2.imwrite(outdir + f.replace('.dcm', '.png'), img) # write png image cv2.im
file = 'large.dcm' read_dcm_file = pydicom.dcmread(file) img_arr = read_dcm_file.pixel_array shape = img_arr.shape image_2d = img_arr.astype(float) dimention = 0 if len(shape) == 4: dimension = shape[1] mid_frame = int(float(img_arr.shape[0]) / 2) if img_arr.shape[3] == 3: print(img_arr[mid_frame].shape) imgexc_render = convert_color_space(img_arr[mid_frame], 'RGB', 'RGB') image_2d = imgexc_render.astype(float) else: dimension = shape[0] if dimension > 512: image_2d_scaled = 255 - (np.maximum(image_2d, 0) / image_2d.max() * 255.0) else: level = 600 window = 1600 if len(shape) == 4: image_2d_scaled = (np.maximum(image_2d, 0) / image_2d.max() * 255.0) else: image_2d_scaled = np.piecewise(image_2d, [ image_2d <= (level - 0.5 - (window - 1) / 2), image_2d > (level - 0.5 + (window - 1) / 2)
def time_rgb_ybr_32_3_2f(self): """Time converting RGB to YBR.""" for ii in range(self.no_runs): convert_color_space(self.arr_32_3_2f, "RGB", "YBR_FULL")