<jupyter_start><jupyter_text>credits: https://stackoverflow.com/a/59786233/10449294<jupyter_code>import numpy as np
from matplotlib import pyplot as plt
import cv2
from pydicom import dcmread
from pydicom.dataset import Dataset, FileDataset
from pydicom.uid import ExplicitVRLittleEndian
import pydicom._storage_sopclass_uids<jupyter_output><empty_output><jupyter_text>read jpg/jpeg/png image as grayscale with int16 data type<jupyter_code>img=cv2.imread('temp.jpeg',0).astype(np.int16)
print(img.shape)
plt.imshow(img.astype(np.uint8),cmap='gray')<jupyter_output>(391, 436)<jupyter_text>create meta data for dicom<jupyter_code>meta = pydicom.Dataset()
meta.MediaStorageSOPClassUID = pydicom._storage_sopclass_uids.MRImageStorage
meta.MediaStorageSOPInstanceUID = pydicom.uid.generate_uid()
meta.TransferSyntaxUID = pydicom.uid.ExplicitVRLittleEndian  
ds = Dataset()
ds.file_meta = meta

ds.is_little_endian = True
ds.is_implicit_VR = False

ds.SOPClassUID = pydicom._storage_sopclass_uids.MRImageStorage
ds.PatientName = "Test^Firstname"
ds.PatientID = "123456"

ds.Modality = "MR"
ds.SeriesInstanceUID = pydicom.uid.generate_uid()
ds.StudyInstanceUID = pydicom.uid.generate_uid()
ds.FrameOfReferenceUID = pydicom.uid.generate_uid()

ds.BitsStored = 16
ds.BitsAllocated = 16
ds.SamplesPerPixel = 1
ds.HighBit = 15

ds.ImagesInAcquisition = "1"
ds.ImagePositionPatient = r"0\0\1"
ds.ImageOrientationPatient = r"1\0\0\0\-1\0"
ds.ImageType = r"ORIGINAL\PRIMARY\AXIAL"
ds.RescaleIntercept = "0"
ds.RescaleSlope = "1"
ds.PixelSpacing = r"1\1"
ds.PhotometricInterpretation = "MONOCHROME2"
ds.PixelRepresentation = 1<jupyter_output><empty_output><jupyter_text>The pydicom dataset has attributes of Rows,Columns,PixelData which should be filled by attributes of target image array<jupyter_code>ds.Rows = img.shape[0]
ds.Columns = img.shape[1]
ds.InstanceNumber = 1
pydicom.dataset.validate_file_meta(ds.file_meta, enforce_standard=True)
ds.PixelData = img.tobytes()

#### Saving image array as dicom 
ds.save_as("out.dcm")<jupyter_output><empty_output><jupyter_text>lets check whether we can affirmatively read the saved dicom<jupyter_code>out=dcmread('out.dcm',force=True)
plt.imshow(out.pixel_array,cmap='gray')
out.pixel_array.shape==img.shape<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11233480176211454, 'fraction_numerical': 0.027312775330396475, 'mean_word_length': 7.380073800738008, 'pattern_counts': {'":': 0, '<': 20, '<?xml version=': 0, '>': 20, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '620911', 'license': 'Apache-2.0', 'n_tokens_mistral': 916, 'n_tokens_neox': 871, 'n_words': 140, 'path': 'jpeg-dicom interoperability.ipynb', 'repo_name': 'vk1996/numpy2dicom', 'size': '2270'}