Beispiel #1
0
    def _convert(self):
        print('open data converving start now')
        tot_convert_time = 0

        for root, dirs, files in os.walk(self.dlserver_path):

            for file in files:
                if '.dcm' in file:
                    dcm_path=os.path.join(root, file)
                    print('dcm path', dcm_path)
                    dicom_read = dicom.read_file(dcm_path)

                    try:

                        if '3D' in dicom_read.SeriesDescription:
                            x_save_path = dcm_path[:dcm_path.find('/upload')+7] + '/x'
                            print('x_save_path', x_save_path)

                            if not os.path.exists(x_save_path):
                                os.makedirs(x_save_path)

                            convert_s_time = time.time()
                            print('save name', x_save_path + '/' + dcm_path[dcm_path.find('/upload')+8:-4] + '.jpg')
                            mritopng.convert_file(dcm_path, x_save_path + '/' + dcm_path[dcm_path.find('/upload')+8:-4] + '.jpg')
                            convert_e_time = time.time()
                            tot_convert_time += convert_e_time - convert_s_time

                    except AttributeError:

                        pass

        print('converting Finished. Converting time', tot_convert_time)
Beispiel #2
0
    def test_convert_file_with_negative_values(self):
        """ Tests DICOM files with negative values, which are clipped to 0 """

        cases = ['000012.dcm', '000017.dcm']
        curr_path = os.path.dirname(os.path.realpath(__file__))

        for case in cases:

            sample_path = os.path.join(curr_path, 'data', 'samples', case)
            expected_path = os.path.join(curr_path, 'data', 'expected',
                                         case + '.png')
            actual_path = os.path.join(tempfile.gettempdir(),
                                       '%s.%s' % (uuid.uuid4(), "png"))

            print('Actual File Path: %s' % actual_path)

            # Try the file conversion
            try:
                mritopng.convert_file(sample_path, actual_path)
            except Exception as err:
                self.fail('%s' % err)

            self.assertTrue(
                filecmp.cmp(actual_path, expected_path),
                'PNG generated from dicom1 does not match the expected version'
            )
    def dicom_to_png(self):
        # get dicom file list
        dcm_file_list = [
            file for file in os.listdir(self.input_path)
            if file.endswith(".dcm")
        ]

        dcm_file_list.sort()

        parent_path = self.input_path + "/../"

        png_dir_name = self.get_dir_name(self.input_path) + "toPng"

        # make new png dir with png name
        png_dir_path = os.path.join(parent_path, png_dir_name)

        utils.maybe_mkdir(png_dir_path)

        for dcm in dcm_file_list:
            dcm_name = dcm[:-4]

            png_name = dcm_name + ".png"

            # convert one dicom file to one png file
            mritopng.convert_file(os.path.join(self.input_path, dcm),
                                  os.path.join(png_dir_path, png_name),
                                  auto_contrast=True)

        print("Successfully process dicom to png your new file created at {}".
              format(png_dir_path))
        return
Beispiel #4
0
def cleanedPhosphorusData():
    default_png = os.path.join(APP_ROOT, 'uploads', 'converted',
                               'Default_MRI.png')
    upload_png = os.path.join(APP_ROOT, 'uploads', 'converted',
                              'Upload_MRI.png')
    upload_dcm = os.path.join(APP_ROOT, 'uploads', 'mri', 'Upload_MRI.dcm')
    return_image = default_png
    encoded_string = "Error while image encoding"

    # Check whether the upload MRI file exist
    try:
        if os.path.isfile(upload_dcm):
            if os.path.isfile(upload_png):
                os.remove(upload_png)
            try:
                # Convert the MRI file to PNG file
                mritopng.convert_file(upload_dcm, upload_png)
                return_image = upload_png
            except Exception as exp:
                app.logger.error(str(exp))

        elif os.path.isfile(upload_png):
            return_image = upload_png

        # Convert the image
        with open(return_image, "rb") as image:
            encoded_string = base64.b64encode(image.read())

    except Exception as exception:
        app.logger.error(str(exception))

    #return send_file(return_image, mimetype='image/png')
    return encoded_string
Beispiel #5
0
    def test_convert_file_auto_contrast(self):
        cases = ['dicom1', '000012.dcm', '000017.dcm']
        curr_path = os.path.dirname(os.path.realpath(__file__))
        os.makedirs(os.path.join(test_out_path, 'auto-contrast'))

        for case in cases:

            sample_path = os.path.join(curr_path, 'data', 'samples', case)
            expected_path = os.path.join(curr_path, 'data', 'expected',
                                         'auto-contrast', case + '.png')
            actual_path = os.path.join(test_out_path, 'auto-contrast',
                                       case + '.png')

            print('Actual File Path: %s' % actual_path)

            # Try the file conversion
            try:
                print('>>> Here')
                mritopng.convert_file(sample_path,
                                      actual_path,
                                      auto_contrast=True)
                print('<<<')
            except Exception as err:
                traceback.print_exc(file=sys.stdout)
                self.fail('%s' % err)

            self.assertTrue(
                filecmp.cmp(actual_path, expected_path),
                'PNG generated from dicom1 does not match the expected version'
            )
Beispiel #6
0
def convertImg(dicomImage):
    print("Image: " + dicomImage)
    outputImg = dicomImage.split('.')
    mritopng.convert_file(os.path.join(folder_path, dicomImage),
                          os.path.join(folder_path, outputImg[0] + '.jpg'),
                          auto_contrast=True)

    convertedImg = os.path.join(folder_path, outputImg[0] + '.jpg')
    return convertedImg
Beispiel #7
0
def convert_dcm_to_png(root_dir, source_dir):
    if not os.path.exists(os.path.join(root_dir, 'png')):
        os.makedirs(os.path.join(root_dir, 'png'))
    dcm_data_path = glob(os.path.join(root_dir, source_dir, '*.dcm'))
    for idx in range(np.shape(dcm_data_path)[0]):
        complit_data_name = re.split('/|[.]|\\\\', dcm_data_path[idx])[-2]
        data_name = re.split('/|[_]', complit_data_name)[0]
        print(os.path.join(root_dir, source_dir, complit_data_name, '.dcm'))
        mritopng.convert_file(dcm_data_path[idx],os.path.join(root_dir, 'png', data_name + '.png'))
Beispiel #8
0
    def test_convert_file(self):
        """ Tests conversion of a single DICOM file """
        curr_path = os.path.dirname(os.path.realpath(__file__))
        sample_path = os.path.join(curr_path, 'data', 'samples', 'dicom1')
        expected_path = os.path.join(curr_path, 'data', 'expected', 'dicom1.png')
        actual_path = os.path.join(test_out_path, 'dicom1.png')

        print('Actual File Path: %s' % actual_path)

        # Try the file conversion
        try:
            mritopng.convert_file(sample_path, actual_path)
        except Exception as err:
            self.fail('%s' % err)

        self.assertTrue(filecmp.cmp(actual_path, expected_path),
                        'PNG generated from dicom1 does not match the expected version')
Beispiel #9
0
    def post(self, request):
        serializer = DicomSerializer(data=request.data)
        filename = str(request.data['dicom'])
        folder_path = os.path.join(settings.BASE_DIR, 'static_files')
        dicom_path = folder_path + '/dicom/' + filename
        if '.dcm' in filename:
            filename = change_extension.splitext(filename)[0]
        png_path = folder_path + '/dicom/png/' + filename + '.png'
        # print(png_path)

        if serializer.is_valid():
            serializer.save()
            # dicom_path = folder_path+str(serializer.data['dicom'])
            makedirs(folder_path + '/dicom/png/', exist_ok=True)
            mritopng.convert_file(dicom_path, png_path)
            png_path = '/media/dicom/png/' + filename + '.png'

            return Response({"path": png_path}, status=201)
        return Response(serializer.errors, status=400)
Beispiel #10
0

RefDs.pixel_array.dtype


# In[6]:


lstFilesDCM[26][:-4]


# In[7]:


# png 파일로 저장
mritopng.convert_file(lstFilesDCM[26], lstFilesDCM[26][:-4]+".png")


# In[8]:


src = cv.imread(lstFilesDCM[26][:-4]+".png",-1)


# In[9]:


type(src)
src.dtype

Beispiel #11
0
# files = glob.glob("*.dcm")
# for file in tqdm(files[:1]):
#     try:
#         fname = file[:-4] + ".png"
#
#         data = pydicom.dcmread(file)
#         img = data.pixel_array
#         print(img.shape)
#         plt.imsave(os.path.join(test_result_path, fname), img, cmap=plt.cm.bone)
#         # Image.save(os.path.join(test_result_path, fname))
#         # cv2.imwrite(os.path.join(test_result_path, fname), img)
#     except:
#         print(f"unexpected error occur: {file}")

print("Converting Test Datasets ... ")
os.chdir(val_dicom_path)
files = glob.glob("*.dcm")
for file in tqdm(files):
    try:
        fname = file[:-4] + ".png"

        mritopng.convert_file(os.path.join(val_dicom_path, file),
                              os.path.join(val_result_path, fname))
        # data = pydicom.dcmread(file)
        # img = data.pixel_array
        # print(img.shape)
        # plt.imsave(os.path.join(test_result_path, fname), img, cmap=plt.cm.bone)
        # Image.save(os.path.join(test_result_path, fname))
        # cv2.imwrite(os.path.join(test_result_path, fname), img)
    except:
        print(f"unexpected error occur: {file}")