欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-04 16:58:58
本文实例讲述了java实现解析dcm医学影像文件并提取文件信息的方法。分享给大家供大家参考,具体如下: 一、安装 首先去github 下载源码,然后执行mvn inst...

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

一、安装

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

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

然后在pom.xml文件中引入该jar包:

<dependency>
  <groupid>org.dcm4che</groupid>
  <artifactid>dcm4che-core</artifactid>
  <version>3.3.2</version>
</dependency>

二、测试类

/**
 * 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; i<j; i++) {//jours
          r.append(numero.charat(i));
          if(i ==7 ){
            if(valuenoun == null ? "dot" == null : valuenoun.equals("dot")){
              r.append('.');
            }else{
              r.append(' ');
            }
          }
        }
        for (int i = 4, j =6; i<j; i++) {
          r.append(numero.charat(i));//the first char value of the sequence is at index zero, the next at index one, and so on, as for array indexing.
          if(i ==5 ){
            if(valuenoun == null ? "dot" == null : valuenoun.equals("dot")){
              r.append('.');
            }else{
              r.append(' ');
            }
          }
        }
        for (int i = 0, j =4; i<j; i++) {
          r.append(numero.charat(i));//the first char value of the sequence is at index zero, the next at index one, and so on, as for array indexing.
        }
        return r.tostring();
      }
    }
    return numero;
  }
  /**
   * read value tag of vr = da
   *
   * if use setdicomobject(readdicomobject(file f)), and getheaderdatevalue(getdicomobject())
   * @param tagnr "0000,0010"
   * @return
   */
  public date getheaderdatevalue(string tagnr) {
    return getheaderdatevalue(totagint(tagnr));
  }
  /**
   * read value tag of vr = da
   *
   * @param tagnr see dcm4che2
   * @return
   */
  public date getheaderdatevalue(int tagnr) {
    return getobject().getdate(tagnr);
  }
  /**
   * 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 totagint(string headernr){
    return integer.parseint(headernr.replaceall(",", ""), 16);
  }
  /**
   * read value tag of vr = da
   * @param tagnr
   * @param dicomobj
   * @return
   */
  public date getheaderdatevalue(int tagnr,attributes dicomobj) {
    return dicomobj.getdate(tagnr);
  }
  /**
   * read value tag of vr = da
   * @param tagnr :"0000,0010"
   * @param dicomobj
   * @return
   */
  public date getheaderdatevalue(string tagnr,attributes dicomobj) {
    return getheaderdatevalue(totagint(tagnr), dicomobj);
  }
  /**
   * remove string ^ in file dicom
   * @param num
   * @return
   */
  public static string textedicom(string num) {
    num = num.replaceall("\\^+", " ");
    return num;
  }
  /**
   * convertor tag to string
   * using vm !=1
   * example result [25, 25]
   * @param tag
   * @return
   */
  public static string getstringtag(attributes object, int tag){
    string tagvalue2[] = object.getstrings(tag);//conversion table in list to string
    string tagvalue = arrays.aslist(tagvalue2).tostring();
    return tagvalue;
  }
  /**
   * convertor tag to string
   * using vm !=1
   * example result 25/25
   * @param object
   * @param tag
   * @return
   */
  public static string getstringtag2(attributes object, int tag){
    string tagvalue2[] = object.getstrings(tag);//conversion table in list to string
    string tagvalue =displaytag.arraytostring(tagvalue2,"\\");
    return tagvalue;
  }
  /**
   * convert an array of strings to one string
   * put the 'separator' string between each element
   * @param a
   * @param separator
   * @return
   */
  public static string arraytostring(string[] a, string separator){
    stringbuffer result = new stringbuffer();
    if(a.length>0) {
      result.append(a[0]);
      for(int i=1;i<a.length;i++){
        result.append(separator);
        result.append(a[i]);
      }
    }
    return result.tostring();
  }
  /**
   * permit display time in hh.mm.ss
   * (0008,0030) at s study time
   * (0008,0031) at s series time
   * (0008,0032) at s acquisition time
   * (0008,0033) at s image time
   * @param tag : giving tag
   * @return
   * @throws ioexception
   */
  public string dicomtime(int tag) throws ioexception{
    if(getobject().contains(tag)==true ){
      string tagvalue = getobject().getstring(tag);
      string tagvaluenotdot = formatnotdot(tagvalue);
      string tagtimefomat = formattimes(tagvaluenotdot);
      return tagtimefomat;
    } else {
      return null;
    }
  }
  /**
   * permit display time in hh.mm.ss.fac
   * (0008,0030) at s study time
   * (0008,0031) at s series time
   * (0008,0032) at s acquisition time
   * (0008,0033) at s image time
   * @param tag : giving tag
   * @return
   * @throws ioexception
   */
  public string dicomtimetotal( int tag) throws ioexception{
    if(getobject().contains(tag)==true ){
      string tagvalue = getobject().getstring(tag);
      string tagtimefomat = formattimes(tagvalue);
      return tagtimefomat;
    } else {
      return null;
    }
  }
  /**
   * permit display time in hh.mm.ss
   * (0008,0030) at s study time
   * (0008,0031) at s series time
   * (0008,0032) at s acquisition time
   * (0008,0033) at s image time
   * @param object : metadata
   * @param tag : value dicom
   * @return new value string
   * @throws ioexception
   */
  public string dicomtime2(attributes object, int tag) throws ioexception{
    string tagvalue = object.getstring(tag);
    string tagvaluenotdot = formatnotdot(tagvalue);
    system.out.println(formattime(tagvaluenotdot));
    string tagtimefomat = formattimes(tagvaluenotdot);
    return tagtimefomat;
  }
  /**
   * permit display time in hh.mm.ss.frac
   * (0008,0030) at s study time
   * (0008,0031) at s series time
   * (0008,0032) at s acquisition time
   * (0008,0033) at s image time
   * @param object : metadata
   * @param tag : value dicom
   * @return new value string
   * @throws ioexception
   */
  public string dicomtime3(attributes object, int tag) throws ioexception{
    string tagvalue = object.getstring(tag);
    string tagtimefomat = formattimes(tagvalue);
    return tagtimefomat;
  }
  /**
   * reads a int value from the dicomheader
   * @param tagnr the tag to read
   * @return the value as int
   */
  public int getheaderintegervalue(int tagnr) {
    return getobject().getint(tagnr,0);
  }
  /**
   *
   * @param tagnr e.g. "0018,0050" to get slice thickness<br>
   * 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<j; i++) {
        r.append(numero.charat(i));
        if ((i % 2 == 1)&(i<5)){
          r.append(':');
        }
      }
      return r.tostring();
    }
    return numero;
  }
  /**
   * round double after dot
   * @param a : value convertor
   * @param n number of decade
   * @return new value
   */
  public double floor(double a, int n){
    double p =math.pow(10.0,n);
    return math.floor((a*p)+0.5)/p;
  }
  /**
   * giving power
   * example:
   *     setfactorpower(10,2)//10^2
   * @param result3
   * @param factor
   * @return
   * @return
   */
  public static double setfactorpower(double result3, double factor){
    return resultfactordix= math.pow(result3, factor);
  }
  /**
   * giving getfactorpower
   */
  public static double getfactorpower(){
    return resultfactordix;
  }
  /**
   * giving pixeldata
   * @param dcmobj
   * @return
   */
  public static int[] lattricepixeldata(attributes dcmobj){
    int[] data = dcmobj.getints(tag.pixeldata);
    return data;
  }
  /**
   * giving pixel data
   * @return
   * @throws ioexception
   */
  public int[] lattricepixeldata2() throws ioexception{
    int[] data = getobject().getints(tag.pixeldata);
    return data;
  }
  /**
   * giving pixel data
   * @param dcmobj
   * @return
   * @throws ioexception
   */
  public byte[] lattricepixeldatabytes(attributes dcmobj) throws ioexception{
    byte[] data = dcmobj.getbytes(tag.pixeldata);
    return data;
  }
  /**
   * giving pixel data
   * @return
   * @throws ioexception
   */
  public byte[] lattricepixeldatabytes2() throws ioexception{
    byte[] data = getobject().getbytes(tag.pixeldata);
    return data;
  }
  /**
   * extraction pixeldata
   * @param raster of dicom
   * @return
   */
  private int[][] extractdata(raster raster) {
    int w = raster.getwidth();
    int h = raster.getheight();
    system.out.printf("w = %d h = %d%n", w, h);
    //writableraster raster = (writableraster) getmyimage();
    int[][] data = new int[h][w];
    for (int y = 0; y < h; y++) {
      for (int x = 0; x < w; x++) {
        data[y][x] =raster.getsample(x, y, 0);
      }
    }
    return data;
  }
  /**
   * extraction pixeldata
   * @return
   */
  private int[] getpixeldata(int[][] data2){
    int h = data2.length;
    int w = data2[0].length;
    int[] array = new int[h*w];
    for(int y = 0; y < h; y++) {
      for(int x = 0; x < w; x++) {
        int index = y*w + x;
        array[index] = data2[y][x];//ligne
      }
    }
    return array;
  }
  /**
   * return value table input
   * @param object
   * @param patient_additional_tags : table int
   *
   * example :
   * public static final int[] tag = {
  0x00080020,
  0x00080022,
  };
   *
   *fileinputstream fis = new fileinputstream(fileinput);
   *dicominputstream dis = new dicominputstream(fis);
   *dicomobject obj = dis.readdicomobject();
   *string nounvalue[] =getvalue(obj,tag);
   *
   * @return
   */
  private static string[] getvalue(attributes object, int[] patient_additional_tags){
    string [] value = new string [patient_additional_tags.length];
    int i =0;
    while (i<patient_additional_tags.length){
      for (int tag : patient_additional_tags) {
        value[i]=object.getstring(tag);
        i++;
      }
//system.out.print(value[0]+"\n");
//system.out.print(value[1]);
    }
    return value;
  }
  /**
   * reading vr = sq
   *
   * @param inputfile : file
   * @param tag : vr =sq
   * @return
   */
  public string[] readitem (file inputfile, int tag){
    displaytag dcm = new displaytag(inputfile);
    sequence seq= dcm.getobject().getsequence(tag);
    string valuestring[] = new string[seq.size()];
    for (int i = 0; i<seq.size(); i++){
      attributes attr = seq.get(i);
      valuestring[i] = attr.tostring();
    }
    return valuestring;
  }
  /**
   * value inside vr = sq
   * @param inputfile : input file
   * @param tagsq : tag vr = sq
   * @param tag : tag inside vr= sq
   * @return
   */
  public string tagitem(file inputfile, int tagsq, int tag){
    string valuestring = null;
    displaytag dcm = new displaytag(inputfile);
    sequence seq= dcm.getobject().getsequence(tagsq);
    attributes attr = seq.get(0);
    valuestring = attr.getstring(tag);
    return valuestring;
  }
  /**
   * les unités spécifiques selon les tags pour vr= sq/ unity specical for tags vr= sq
   * @param tag :
   *   - regionspatialformat
   *   - regiondatatype
   *   - physicalunitsxdirection
   *   - physicalunitsxdirection
   *   - pixelcomponentphysicalunits
   *
   *
   *
   * @param result : value string
   */
  public void unit(int tag, string result){
    if (tag == tag.regionspatialformat ){
      val2= integer.valueof(result).intvalue();//convertie en int
      switch(val2)
      {
        case 5:
          setnoununit("graphics");
          break;
        case 4:
          setnoununit("wave form(physiological traces, doppler traces,...");
          break;
        case 3:
          setnoununit("spectral(cw or pw doppler");
          break;
        case 2:
          this.setnoununit("m-mode(tissue or flow)");
          break;
        case 1:
          this.setnoununit("2d(tissue or flow");
          break;
        case 0:
          setnoununit("none or not applicable");
          break;
        default:
          break;
      }
    }else if (tag == tag.regiondatatype ){
      val2= integer.valueof(result).intvalue();//convertie en int
      switch(val2)
      {
        case 12:
          setnoununit("orther physiological(amplitude vs. time)");
          break;
        case 11:
          setnoununit("d(area)/dt");
          break;
        case 10:
          setnoununit("area trace");
          break;
        case 9:
          setnoununit("d(volume)/dt trace");
          break;
        case 8:
          setnoununit("volume trace");
          break;
        case 7:
          setnoununit("doppler max trace");
          break;
        case 6:
          this.setnoununit("doppler mode trace");
          break;
        case 5:
          this.setnoununit("doppler mean trace");
          break;
        case 4:
          setnoununit("cw spectral doppler");
          break;
        case 3:
          this.setnoununit("pw spectral doppler");
          break;
        case 2:
          this.setnoununit("color flow");
          break;
        case 1:
          this.setnoununit("tissue");
          break;
        case 0:
          this.setnoununit("none or not applicable");
          break;
        default:
          break;
      }
      switch (result) {
        case "a":
          this.setnoununit("ecg trace");
          break;
        case "b":
          this.setnoununit("pulse trace");
          break;
        case "c":
          this.setnoununit("phonocardiogram trace");
          break;
        case "d":
          this.setnoununit("gray bar");
          break;
        case "e":
          this.setnoununit("color bar");
          break;
        case "f":
          this.setnoununit("integrated backscatter");
          break;
        default:
          return;
      }
    }else
    if (tag == tag.physicalunitsxdirection || tag == tag.physicalunitsxdirection || tag == tag.pixelcomponentphysicalunits){
      val2= integer.valueof(result).intvalue();//convertie en int
      switch(val2)
      {
        case 9:
          setnoununit("cm*cm.pixel/sec");
          break;
        case 8:
          setnoununit("cm*cm/pixel");
          break;
        case 7:
          setnoununit("cm*pixel/sec");
          break;
        case 6:
          this.setnoununit("db*pixel/seconds");
          break;
        case 5:
          this.setnoununit("hertz/pixel");
          break;
        case 4:
          setnoununit("seconds/pixel");
          break;
        case 3:
          this.setnoununit("cm/pixel");
          break;
        case 2:
          this.setnoununit("db/pixel");
          break;
        case 1:
          this.setnoununit("percent/pixel");
          break;
        case 0:
          this.setnoununit("none or not applicable");
          break;
        default:
          break;
      }
      switch (result) {
        case "a":
          this.setnoununit("cm*cm*cm/pixel");
          break;
        case "b":
          this.setnoununit("cm*cm*cm*pixel/sec");
          break;
        case "c":
          this.setnoununit("degrees");
          break;
      }
    }else if (tag == tag.pixelcomponentdatatype ){
      val2= integer.valueof(result).intvalue();//convertie en int
      switch(val2)
      {
        case 9:
          setnoununit("computed border");
          break;
        case 8:
          setnoununit("integrated backscatter");
          break;
        case 7:
          setnoununit("color bar");
          break;
        case 6:
          this.setnoununit("gray bar");
          break;
        case 5:
          this.setnoununit("color flow intensity");
          break;
        case 4:
          setnoununit("color flow variance");
          break;
        case 3:
          this.setnoununit("color flow velocity");
          break;
        case 2:
          this.setnoununit("spectral doppler");
          break;
        case 1:
          this.setnoununit("tissue");
          break;
        case 0:
          this.setnoununit("none or not applicable");
          break;
        default:
          break;
      }
      if("a".equals(result)){
        this.setnoununit("tissue classification");
      }
    }
    else {
      this.setnoununit("none or not applicable");
    }
  }
  /**
   * enregistre l'unité des items/ put unity of items
   * @param noununit
   * @return this.noununit = noununit
   */
  public string setnoununit(string noununit){
    return this.noununit = noununit;
  }
  /**
   * on obtient l'unité des items./giving unity of items
   * @return le nom de l'unité
   */
  public string getnoununit(){
    return noununit;
  }
  /**
   * special ratio spatial toutes les unites sont en mm/ giving tag ratio spatial of mm
   * @param tag : entree choisi
   *     - physicalunitsxdirection
   *     - physicalunitsydirection
   *     -pixelcomponentphysicalunits
   *
   * @param result: prend l'unite
   */
  public void unitratiospatial(int tag, string result){
    if (tag == tag.physicalunitsxdirection || tag == tag.physicalunitsydirection || tag == tag.pixelcomponentphysicalunits){
      val2= integer.valueof(result).intvalue();//convertie en int
      switch(val2)
      {
        case 9:
          double valuespatial1 = getvaleurtagitemdoubleratio()* setfacteurpuissance(10,1);
          settagitemdoubleratio(valuespatial1);//prend la valeur
          setnoununitratio("mm*mm.pixel/sec");
          break;
        case 8:
          double valuespatial2 = getvaleurtagitemdoubleratio()* setfacteurpuissance(10,1);
          settagitemdoubleratio(valuespatial2);//prend la valeur
          setnoununitratio("mm*mm/pixel");
          break;
        case 7:
          setnoununitratio("mm*pixel/sec");
          break;
        case 6:
          this.setnoununitratio("db*pixel/seconds");
          break;
        case 5:
          this.setnoununitratio("hertz/pixel");
          break;
        case 4:
          setnoununitratio("seconds/pixel");
          break;
        case 3:
          this.setnoununitratio("mm/pixel");
          break;
        case 2:
          this.setnoununitratio("db/pixel");
          break;
        case 1:
          this.setnoununitratio("percent/pixel");
          break;
        case 0:
          this.setnoununitratio("none or not applicable");
          break;
        default:
          break;
      }
      switch (result) {
        case "a":
          double valuespatial3 = getvaleurtagitemdoubleratio()* setfacteurpuissance(10,2);
          settagitemdoubleratio(valuespatial3);//prend la valeur
          this.setnoununitratio("mm*mm*mm/pixel");
          break;
        case "b":
          double valuespatial4 = getvaleurtagitemdoubleratio()* setfacteurpuissance(10,2);
          settagitemdoubleratio(valuespatial4);//prend la valeur
          this.setnoununit("mm*mm*mm*pixel/sec");
          break;
        case "c":
          this.setnoununit("degrees");
          break;
      }
    }
  }
  /**
   * prend la valeur d'un ratio spatial/put value ratio spatial
   * @param valuespatial
   * @return
   */
  public double settagitemdoubleratio(double valuespatial){
    return this.valuespatial = valuespatial;
  }
  /**
   * donne la valeur du ratio/diving value ratio spatial
   * @return
   */
  public double getvaleurtagitemdoubleratio(){
    return valuespatial;
  }
  /**
   * donne les valeurs calculer des puissances/ put and computing power
   * @param result3
   * @param facteur
   * @return
   * @return
   */
  public static double setfacteurpuissance(double result3, double facteur){
    return resultfacteurdix = math.pow(result3, facteur);
  }
  /**
   * obtient la valeur de puissance/ giving value power
   * @return
   */
  public static double getfacteurpuissance(){
    return resultfacteurdix;
  }
  /**
   * enregistre l'unite des items /put unity unity items
   * @return this.noununit = noununit
   */
  public string setnoununitratio(string noununitratio){
    return this.noununitratio = noununitratio;
  }
  /**
   * on obtient l'unite des items./giving unity items
   * @return le nom de l'unité
   */
  public string getnoununitratio(){
    return noununitratio;
  }
  /**
   * prend la valeur interne d'un tag item/ put tag item
   * @param result
   * @return
   */
  public string settagitem(string result){
    return this.result = result;
  }
  /**
   * donne la valeur du tag rechercher/giving a value of tag seek
   * @return le string de la valeur rechercher du tag dans un item
   */
  public string getvaleurtagitem(){
    return result;
  }
  /**
   * prend la valeur interne d'un tag item/ put the value tag iteù
   * @return
   */
  public double settagitemdouble(double result2){
    return this.result2 = result2;
  }
  /**
   * donne la valeur du tag rechercher/giving the value tag
   * @return le double de la valeur rechercher du tag dans un item
   */
  public double getvaleurtagitemdouble(){
    return result2;
  }
  /**
   * reads a string value from tag dicom (dcm4che2)
   * @param tagnr the tag to read
   * @return the value as string
   * returns the specific character set defined by attribute specific character set (0008,0005)
   * of this or the root data set, if this is a nested data set containing in a sequence eleme
   */
  public string getheaderstringvalue(int tagnr) {
    try {
      attributes elem = getobject();
      elem.setspecificcharacterset("gb18030");
      string val = elem.getstring(tagnr);
      if (val == null) {
        val = "";
      }
      return val;
    } catch (exception e) {
      return "";
    }
  }
  /**
   * reads a string value from tag dicom (dcm4che2)
   * @param tagnr the tag to read
   * @return the value as string
   * returns the specific character set defined by attribute specific character set (0008,0005)
   * of this or the root data set, if this is a nested data set containing in a sequence eleme
   */
  public string[] getheaderstringvalues(int tagnr) {
    try {
      system.out.println(222);
      attributes elem = getobject();
      elem.setspecificcharacterset("gb18030");
      string[] val = elem.getstrings(tagnr);
      return val;
    } catch (exception e) {
      return null;
    }
  }
  /**
   * reads a string value from the dicomheader
   * @param tagnr the tag to read
   * @param dcmelement
   * @return the value as string
   */
  public string getheaderstringvalue(attributes dcmelement, int tagnr) {
    try {
      system.out.println(333);
        /* dcmelement.setspecificcharacterset("iso_ir 100"); */
      dcmelement.setspecificcharacterset("gb18030");
      string val = dcmelement.getstring(tagnr);
      if (val == null) {
        val = "";
      }
      return val;
    } catch (exception e) {
      return "";
    }
  }
  /**
   *reads the tag (group,element)
   * @param headernr e.g. "0018,0050" to get slice thickness<br>
   * @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程序设计有所帮助。