Java实现解析dcm医学影像文件并提取文件信息的方法示例

本文实例讲述了Java实现解析dcm医学影像文件并提取文件信息的方法。分享给大家供大家参考,具体如下:

一、安装

首先去Github 下载源码,然后执行mvn install进行本地安装,Maven中央仓库,竟然没有该jar。。安装成功之后如下:

Java实现解析dcm医学影像文件并提取文件信息的方法示例_第1张图片

然后在POM.XML文件中引入该jar包:


  org.dcm4che
  dcm4che-core
  3.3.2


二、测试类

/**
 * projectName: xxx
 * fileName: DisplayTag.java
 * packageName: com.xxxx.xxxx.common.util
 * date: 2018-03-26 10:07
 * copyright(c) 2017-2020 xxx公司
 */
package com.gz.medicine.common.util;
import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;
import java.sql.Time;
import java.util.Arrays;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dcm4che3.data.Attributes;
import org.dcm4che3.data.ElementDictionary;
import org.dcm4che3.data.Fragments;
import org.dcm4che3.data.Sequence;
import org.dcm4che3.data.Tag;
import org.dcm4che3.data.VR;
import org.dcm4che3.io.DicomEncodingOptions;
import org.dcm4che3.io.DicomInputStream;
import org.dcm4che3.io.DicomOutputStream;
import org.dcm4che3.util.SafeClose;
import java.awt.image.Raster;
import java.io.IOException;
import java.util.Arrays;
/**
 * @version: V1.0
 * @author: fendo
 * @className: DisplayTag
 * @packageName: com.xxxx.xxxx.common.util
 * @description: Tag解析
 * @data: 2018-03-26 10:07
 **/
public final class DisplayTag {
  private static Attributes obj=null, object =null;
  private static DicomInputStream din;
  private static double resultFactorDix;
  private String result = null;
  private Double result2 = null;
  private String nom = null;
  private String nounString = null;
  private int val2 = 0;
  private int valeurReturn;
  private String nounUnit = null;
  private static double resultFacteurDix = 0;
  private Double valueSpatial = null;
  private String nounUnitRatio = null;
  private  DicomInputStream dis;
  private static final char[] HEX_DIGITS = {
      '0' , '1' , '2' , '3' , '4' , '5' ,
      '6' , '7' , '8' , '9' , 'A' , 'B' ,
      'C' , 'D' , 'E' , 'F'
  };
  private DicomEncodingOptions encOpts = DicomEncodingOptions.DEFAULT;
  private static ElementDictionary dict = ElementDictionary.getStandardElementDictionary();
  public DisplayTag(File file ){
    try {
      setObject(loadDicomObject(file) );
    } catch (IOException ex) {
      Logger.getLogger(DisplayTag.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
  /**
   * Read metadata of Dicom 3.0
   * @param f : input file
   * @return Attributes
   * @throws IOException
   */
  public static Attributes loadDicomObject(File f) throws IOException {
    if (f == null){
      return null;
    }else{
      DicomInputStream dis = new DicomInputStream(f);
      //attr.setSpecificCharacterSet("GBK");
      return dis.readDataset(-1, -1);
    }
  }
  /**
   * Put attribut
   * @param obj
   */
  public void setObject(Attributes obj){
    this.obj = obj;
  }
  /**
   * Giving attribut of metadata
   * @return
   */
  public static Attributes getObject(){
    return obj;
  }
  /**
   * Display metadata
   * @param file : file inout
   * @throws IOException
   */
  public String readTagDicom(File file) throws IOException{
    din = new DicomInputStream(file);
    object = din.readFileMetaInformation() ;
    String value = object.toString();
    object = din.readDataset(-1, -1);
    return value;
  }
  /**
   * Permet d'afficher l'heure d'une valeur dicom en standard international yyyy.mm.dd/ Permit display time in format yyyy.mm.dd
   * @param Tag : valeur du tag / int tag
   * @param valueBool : si true Format yyyy.mm.dd sinon format dd.mm.yyyy/ if true then format yyyy.mm.dd else dd.mm.yyyy
   * @param valueNoun : "dot" mettre la date en format yyyy.mm.dd ou dd.mm.yyyy sinon en format yyyy mm dd ou dd mm yyyy/ "dot" put yyyy.mm.dd or dd.mm.dd or dd.mm.yyyy else yyyy mm or dd mm yyyy
   * @return afficher le string du tag selon le standard international/ return string Date
   * @throws IOException
   */
  public String dicomDate(int Tag,boolean valueBool, String valueNoun) throws IOException{
    if(getObject().contains(Tag)==true ){
      String tagValue = getObject().getString(Tag);
      String tagDayFomat = FormatDate(tagValue,valueBool,valueNoun);
      return tagDayFomat;
    }else{
      return null;
    }
  }
  /**
   * Permet d'afficher l'heure d'une valeur dicom en standard international yyyy.mm.dd/ Permit display a time in metadata for yyyy.mm.dd
   * @param object
   * @param Tag : valeur du tag/ value of tag
   * @param valueBool : si true Format yyyy.mm.dd sinon format dd.mm.yyyy/ if true format yyyy.mm.dd else dd.mm.yyyy
   * @param valueNoun : "dot" mettre la date en format yyyy.mm.dd ou dd.mm.yyyy sinon en format yyyy mm dd ou dd mm yyyy/dot" put yyyy.mm.dd or dd.mm.dd or dd.mm.yyyy else yyyy mm or dd mm yyyy
   * @return afficher le string du tag selon le standard international/ return string date
   * @throws IOException
   */
  public static String dicomDate(Attributes object , int Tag,boolean valueBool, String valueNoun) throws IOException{
    String tagValue = object.getString(Tag);
    String tagDayFomat = FormatDate(tagValue,valueBool,valueNoun);
    return tagDayFomat;
  }
  /**
   * Format tag
   * @param Numero : String date
   * @param valueBool : if true Format yyyy.mm.dd else format dd.mm.yyyy
   * @param valueNoun : "dot" put the date in format yyyy.mm.dd or dd.mm.yyyy else in format yyyy mm dd or dd mm yyyy
   * @return
   */
  public static String FormatDate(String Numero, boolean valueBool,String valueNoun) {
    if (Numero.matches("^[0-9]*$")) {//If la chaine de caractère est un nombre ou un chiffre
      StringBuffer r = new StringBuffer();
      if (valueBool ==true){//Format yyyy.mm.dd
        for (int i = 0, j = Numero.length(); i < j; i++) {
          r.append(Numero.charAt(i));
          if ((i == 3)||(i == 5) ){
            if(valueNoun == null ? "dot" == null : valueNoun.equals("dot")){
              r.append('.');
            }else{
              r.append(' ');
            }
          }
        }
        return r.toString();
      }else{
        for (int i = 6, j =8; i0) {
      result.append(a[0]);
      for(int i=1;i
   * or "0008,0102#0054,0220" to get the Coding Scheme Designator after View Code Sequence
   * @return int
   */
  public int getHeaderIntegerValue(String tagNr) {
    return getHeaderIntegerValue(toTagInt(tagNr));
  }
  /**
   * checks if the Header contains the given tag
   * @param tagNr
   * @return
   */
  public boolean containsHeaderTag(String tagNr) {
    return containsHeaderTag(toTagInt(tagNr));
  }
  /**
   * checks if the Header contains the given tag
   * @param tagNr
   * @return
   */
  public boolean containsHeaderTag(int tagNr) {
    return getObject().contains(tagNr);
  }
  /**
   * returns the name of the given Tag
   * @param tagNr
   * @return
   */
  public static String getHeaderName(int tagNr) {
    return dict.keywordOf(tagNr);
  }
  /**
   * returns the name of the given Header field
   * @param tagNr
   * @return the name of the Field e.g. Patients Name
   */
  public String getHeaderName(String tagNr) {
    try {
      return getHeaderName(toTagInt(tagNr));
    } catch (Exception e) {
      return "";
    }
  }
  /**
   * returns the String representation of the given header field
   * if it exists in the header
   * @param tagNr
   * @return
   */
  public String getHeader(int tagNr) {
    try {
      String dcmele = getObject().getString(tagNr);
      return toElementString(dcmele, tagNr);
    } catch (Exception e) {
      return "";
    }
  }
  private static String toElementString(String dcmele,int tag) {
    StringBuffer sb = new StringBuffer();
    int TAG[] = getObject().tags();
    StringBuffer append = sb.append(TAG)
        .append(" [").append(getObject().getVR(tag)).append("] ")
        .append(object.tags()).append(": ")
        .append(dcmele);
    return sb.toString();
  }
  /**
   * checks wether the header is empty or not
   * @return
   */
  public boolean isEmpty() {
    if (getObject() == null || getObject().isEmpty()) {
      return true;
    }
    return false;
  }
  /**
   * Converts the string representation of a header number
   * e.g. 0008,0010 to the corresponding integer as 0x00080010
   * as used in the @see org.dcm4che2.data.Tag
   * @param headerNr e.g. 0008,0010
   * @return 0x00080010 as int
   */
  public static int toTagInt2(String headerNr){
    return Integer.parseInt(headerNr.replaceAll(",", ""), 16);
  }
  /**
   * Removing comma in String
   * @param num
   * @return
   */
  public static String formatNotDot(String num) {
    num = num.trim().replaceAll("[^0-9\\+]", "");
    if (num.matches("^0*$")){
      num = "";
    }
    return num;
  }
  /**
   * Format
   * hh.mm.ss
   * @param Numero
   * @return
   */
  public static String FormatTime(String Numero) {
    if (Numero.matches("^[0-9]*$")) {
      StringBuilder r = new StringBuilder();
      for (int i = 0, j = 6; i < j; i++) {
        r.append(Numero.charAt(i));
        if ((i % 2 == 1) && (i < (j - 1))){
          r.append(':');
        }
      }
      return r.toString();
    }
    return Numero;
  }
  /**
   * Format
   * hh.mm.ss.frac
   * @param Numero
   * @return
   */
  public static String FormatTimes(String Numero) {
    if (Numero.matches("^[0-9].*$")) {
      StringBuilder r = new StringBuilder();
      for (int i = 0,j=Numero.length();i
   * @return String
   */
  public String getHeaderStringValue(String headerNr) {
    headerNr = headerNr.replaceAll("xx", "00").replaceAll("XX", "00");
    return getHeaderStringValue(toTagInt(headerNr));
  }
  /**
   * Giving time a tag ("xxxx,")
   * @param tagNr
   * @return
   */
  public Time getHeaderTimeValue(String tagNr) {
    return getHeaderTimeValue(toTagInt(tagNr));
  }
  /**
   * Giving time a tag
   * @param tagNr
   * @return time
   */
  public Time getHeaderTimeValue(int tagNr) {
    String time = getHeaderStringValue(tagNr);
    if (time.length() != 6){
      return null;
    }
    try {
      int hour = Integer.parseInt(time.substring(0,2));
      int min = Integer.parseInt(time.substring(2,4));
      int sec = Integer.parseInt(time.substring(4,6));
      return new Time(hour,min,sec);
    } catch (Exception e) {
    }
    return null;
  }
  /**
   * retrieves a specific HeaderTag that is inside anotehr tag
   * or "0008,0102, 0054,0220" to get the Coding Scheme Designator after View Code Sequence
   * @return String
   *  * @param tagHierarchy; e.g. {Tag.UID, Tag.SOPInstanceUID, Tag.CodeMeaning}
   * @return
   */
  public String getHeaderValueInsideTag(int[] tagHierarchy) {
    try {
      for (int i = 0; i < tagHierarchy.length-1; i++) {
        return getObject().getString(tagHierarchy[i]);
      }
    } catch (Exception e) {
      String tags = "";
      for (int i = 0; i < tagHierarchy.length; i++) {
        tags += toTagString(tagHierarchy[i]) + " ";
      }
      return "";
    }
    return null;
  }
  /**
   * converts the int representation of a header number
   * e.g. 0x00080010 to the corresponding String 0008,0010
   * @return 0008,0010 as String
   */
  public static String toTagString(int tagNr) {
    return shortToHex(tagNr >> 16) +
        ',' + shortToHex(tagNr);
  }
  public static String shortToHex(int val) {
    char[] ch = new char[4];
    shortToHex(val, ch, 0);
    return new String(ch);
  }
  public static StringBuffer shortToHex(int val, StringBuffer sb) {
    sb.append(HEX_DIGITS[(val >> 12) & 0xf]);
    sb.append(HEX_DIGITS[(val >> 8) & 0xf]);
    sb.append(HEX_DIGITS[(val >> 4) & 0xf]);
    sb.append(HEX_DIGITS[val & 0xf]);
    return sb;
  }
  public static void shortToHex(int val, char[] ch, int off) {
    ch[off] = HEX_DIGITS[(val >> 12) & 0xf];
    ch[off+1] = HEX_DIGITS[(val >> 8) & 0xf];
    ch[off+2] = HEX_DIGITS[(val >> 4) & 0xf];
    ch[off+3] = HEX_DIGITS[val & 0xf];
  }
  /**
   * Create file output dicom
   * @param fileOutput : file output
   * @throws IOException
   *
   *
   * Example:
   *
   *
   *
   *
   */
  public void writeTo(File fileOutput, Attributes fmi, Attributes object) throws IOException {
    DicomOutputStream dos = new DicomOutputStream( new File (fileOutput +".dcm"));
    dos.setEncodingOptions(encOpts);
    dos.writeDataset(fmi, object);
    dos.finish();
    dos.flush();
  }
  /**
   * Writting
   * @param fileOutput
   * @param h
   * @param w
   * @throws IOException
   */
  public void writeToSegment(File fileOutput, int h, int w) throws IOException{
    DicomOutputStream dos = new DicomOutputStream( new File (fileOutput +".dcm"));
    dos.setEncodingOptions(encOpts);
  }
  /**
   * Create overlay in pixelData
   * @param object
   */
  public void overlayCreate(Attributes object){
    int position = object.getInt( Tag.OverlayBitPosition, 0 );
    if( position == 0 ) {
      return;
    }
    int bit = 1 << position;
    int[] pixels = object.getInts( Tag.PixelData );
    int count = 0;
    for( int pix : pixels )
    {
      int overlay = pix & bit;
      pixels[ count++ ] = pix - overlay;
    }
    object.setInt( Tag.PixelData, VR.OW, pixels );
  }
  /**
   * dicom.setString(Tag.PerformingPhysicianName, VR.PN, "Jean");
   dicom.setString(Tag.AdmittingDiagnosesDescription, VR.LO, "CHU");
   Sequence seq= dicom.newSequence(Tag.AnatomicRegionSequence,0);
   Attributes dicom2 = new Attributes();
   * @param dicom
   */
  public void setItem(Attributes dicom, int TagSequenceName){
    Sequence seq= dicom.newSequence(TagSequenceName,0);
    dicom.setString(Tag.CodingSchemeDesignator, VR.SH, "SRT");
    dicom.setString(Tag.CodeValue, VR.SH, "T-AA000");
    dicom.setString(Tag.CodeMeaning, VR.LO, "Eye");
    seq.add(dicom);
  }
  public static void main(String[] args) throws Exception {
    File file = new File("C:\\Users\\fendo\\Documents\\WeChat Files\\fen_do\\Files\\1234.dcm");
    DisplayTag d = new DisplayTag(file);
    @SuppressWarnings("static-access")
    Attributes attrs = d.loadDicomObject(file);
    //输出所有属性信息
    System.out.println("所有信息: " + attrs);
    //获取行
    int row = attrs.getInt(Tag.Rows, 1);
    //获取列
    int columns = attrs.getInt(Tag.Columns, 1);
    //窗宽窗位
    float win_center = attrs.getFloat(Tag.WindowCenter, 1);
    float win_width = attrs.getFloat(Tag.WindowWidth, 1);
    System.out.println("" + "row=" + row + ",columns=" + row + ",row*columns = " + row * columns);
    String patientName = attrs.getString(Tag.PatientName, "");
    System.out.println("姓名:" + patientName);
    //生日
    String patientBirthDate = attrs.getString(Tag.PatientBirthDate, "");
    System.out.println("生日:" + patientBirthDate);
    //机构
    String institution = attrs.getString(Tag.InstitutionName, "");
    System.out.println("机构:" + institution);
    //站点
    String station = attrs.getString(Tag.StationName, "");
    System.out.println("站点:" + station);
    //制造商
    String Manufacturer = attrs.getString(Tag.Manufacturer, "");
    System.out.println("制造商:" + Manufacturer);
    //制造商模型
    String ManufacturerModelName = attrs.getString(Tag.ManufacturerModelName, "");
    System.out.println("制造商模型:" + ManufacturerModelName);
    //描述--心房
    String description = attrs.getString(Tag.StudyDescription, "");
    System.out.println("描述--心房:" + description);
    //描述--具体
    String SeriesDescription = attrs.getString(Tag.SeriesDescription, "");
    System.out.println("描述--具体:" + SeriesDescription);
    //描述时间
    String studyData = attrs.getString(Tag.StudyDate, "");
    System.out.println("描述时间:" + studyData);
    byte[] bytename = attrs.getBytes(Tag.PatientName);
    System.out.println("姓名: " + new String(bytename,"gb18030"));
    byte[] bytesex = attrs.getBytes(Tag.PatientSex);
    System.out.println("性别: " + new String(bytesex,"gb18030"));
  }
}

输出如下:

所有信息: (0008,0005) CS [ISO_IR 100] SpecificCharacterSet
(0008,0008) CS [ORIGINAL\PRIMARY] ImageType
(0008,0016) UI [1.2.840.10008.5.1.4.1.1.1.1] SOPClassUID
(0008,0018) UI [1.2.840.113619.2.203.4.2147483647.1486521160.448521] SOPInstan
(0008,0020) DA [20170208] StudyDate
(0008,0021) DA [20170208] SeriesDate
(0008,0022) DA [20170208] AcquisitionDate
(0008,0023) DA [20170208] ContentDate
(0008,002A) DT [20170208103237.000000] AcquisitionDateTime
(0008,0030) TM [103154.000] StudyTime
(0008,0031) TM [103158.000] SeriesTime
(0008,0032) TM [103237.000] AcquisitionTime
(0008,0033) TM [103240.000] ContentTime
(0008,0050) SH [T77792] AccessionNumber
(0008,0060) CS [DX] Modality
(0008,0068) CS [FOR PRESENTATION] PresentationIntentType
(0008,0070) LO ["GE Healthcare"] Manufacturer
(0008,0080) LO [HeFei RICH] InstitutionName
(0008,0081) ST [Not Initialized
Not Initialized
HeFei
AnHui
Not Initialize(0008,0090) PN [] ReferringPhysicianName
(0008,1010) SH [082407110134] StationName
(0008,1030) LO [ACHEST] StudyDescription
(0008,103E) LO [Chest] SeriesDescription
(0008,1040) LO [Not Initialized] InstitutionalDepartmentName
(0008,1050) PN [] PerformingPhysicianName
(0008,1090) LO ["Definium 6000"] ManufacturerModelName
(0008,1110) SQ [] ReferencedStudySequence
(0008,1120) SQ [] ReferencedPatientSequence
(0008,2112) SQ [1 Items] SourceImageSequence
>Item #1
>(0008,1150) UI [1.2.840.10008.5.1.4.1.1.1.1.1] ReferencedSOPClassUID
>(0008,1155) UI [1.2.840.113619.2.203.4.2147483647.1486521157.927189] Referenc
(0008,2218) SQ [1 Items] AnatomicRegionSequence
>Item #1
>(0008,0100) SH [T-D3000] CodeValue
>(0008,0102) SH [SNM3] CodingSchemeDesignator
>(0008,0104) LO [Chest] CodeMeaning
(0010,0010) PN [zhang^xiao di] PatientName
(0010,0020) LO [T77792] PatientID
(0010,0030) DA [19860618] PatientBirthDate
(0010,0032) TM [] PatientBirthTime
(0010,0040) CS [F] PatientSex
(0010,1010) AS [030Y] PatientAge
(0010,1030) DS [] PatientWeight
(0011,0010) LO [GEMS_GDXE_FALCON_04]
(0011,1003) UI [1.2.840.113619.2.203.4.2147483647.1486521118.562807]
(0011,1004) CS [SE]
(0011,1005) UI [1.2.840.113619.2.203.4.2147483647.1486521152.970120]
(0011,1006) DS [0.083936]
(0011,1009) SL [0]
...
row=2021,columns=2021,row*columns = 4084441
姓名:zhang^xiao di
生日:19860618
机构:HeFei RICH
站点:082407110134
制造商:"GE Healthcare"
制造商模型:"Definium 6000"
描述--心房:ACHEST
描述--具体:Chest
描述时间:20170208
姓名: zhang^xiao di
性别: F

更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java文件与目录操作技巧汇总》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

你可能感兴趣的:(Java实现解析dcm医学影像文件并提取文件信息的方法示例)