把图象文件转换成XML格式文件

把图象文件转换成XML格式文件,第1张

利用 NET 框架下的FromBase String和ToBase String方法可以很容易地实现图象文件和XML文件的互换 这样可以轻易解决以XML格式保存图片的问题裤晌雹 代码如下 Public Class Form Inherits System Windows Forms Form#Region Windows 窗体设计器生成的代码 Public Sub New() 谨埋 MyBase New()InitializeComponent()在 InitializeComponent() 调用之后添加任何初始化End Sub窗体重写处置以清理组件列表 Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)If disposing ThenIf Not (ponents Is Nothing) Thenponents Dispose()End IfEnd IfMyBase Dispose(disposing)End SubWindows 窗胡帆体设计器所必需的Private ponents As System ComponentModel IContainer注意 以下过程是 Windows 窗体设计器所必需的可以使用 Windows 窗体设计器修改此过程 不要使用代码编辑器修改它 Friend WithEvents Button As System Windows Forms ButtonFriend WithEvents Button As System Windows Forms ButtonFriend WithEvents PictureBox As System Windows Forms PictureBoxFriend WithEvents Button As System Windows Forms ButtonFriend WithEvents Label As System Windows Forms LabelFriend WithEvents Label As System Windows Forms Label<System Diagnostics DebuggerStepThrough()>Private Sub InitializeComponent()Me Button = New System Windows Forms Button()Me Button = New System Windows Forms Button()Me PictureBox = New System Windows Forms PictureBox()Me Button = New System Windows Forms Button()Me Label = New System Windows Forms Label()Me Label = New System Windows Forms Label()Me SuspendLayout()Button Me Button Location = New System Drawing Point( )Me Button Name = Button Me Button Size = New System Drawing Size( )Me Button TabIndex = Me Button Text = 将图象保存成XML Button Me Button Location = New System Drawing Point( )Me Button Name = Button Me Button Size = New System Drawing Size( )Me Button TabIndex = Me Button Text = 从XML中得到图象 PictureBox Me PictureBox Location = New System Drawing Point( )Me PictureBox Name = PictureBox Me PictureBox Size = New System Drawing Size( )Me PictureBox TabIndex = Me PictureBox TabStop = FalseButton Me Button Location = New System Drawing Point( )Me Button Name = Button Me Button Size = New System Drawing Size( )Me Button TabIndex = Me Button Text = 浏览图片… Label Me Label Location = New System Drawing Point( )Me Label Name = Label Me Label Size = New System Drawing Size( )Me Label TabIndex = Label Me Label Location = New System Drawing Point( )Me Label Name = Label Me Label Size = New System Drawing Size( )Me Label TabIndex = Me Label Text = 【孟宪会之精彩世界】 Form Me AutoScaleBaseSize = New System Drawing Size( )Me ClientSize = New System Drawing Size( )Me Controls AddRange(New System Windows Forms Control() {Me Label Me Label Me Button Me PictureBox Me Button Me Button })Me Name = Form Me Text = 图象文件和XML格式文件互换例子 Me ResumeLayout(False)End Sub#End RegionPrivate MyFile As String = Private MyFileExt As String = Private Sub Button _Click(ByVal sender As System Object ByVal e As System EventArgs) _Handles Button ClickDim pic As StringDim MyXml As System Xml XmlDocument = New System Xml XmlDocument()MyXml Load( c:\MyPhoto xml )Dim picNode As System Xml XmlNodepicNode = MyXml SelectSingleNode( /pic/photo )pic = picNode InnerTextDim memoryStream As System IO MemoryStreammemoryStream = New System IO MemoryStream(Convert FromBase String(pic))Me PictureBox Image = New System Drawing Bitmap(memoryStream)memoryStream Close()End SubPrivate Sub Button _Click(ByVal sender As System Object ByVal e As System EventArgs) _Handles Button ClickIf MyFile = ThenMessageBox Show( 请选择一个图片! 错误 MessageBoxButtons OK MessageBoxIcon Warning)Exit SubEnd IfDim MyImg As System Drawing Image = MyImg FromFile(MyFile)Dim memoryStream As System IO MemoryStream = New System IO MemoryStream()MyImg Save(memoryStream GetImageType(MyFileExt))Dim b() As Byteb = memoryStream GetBuffer()Dim pic As String = Convert ToBase String(b)memoryStream Close()Dim MyXml As System Xml XmlDocument = New System Xml XmlDocument()MyXml LoadXml( <pic><name>孟宪会</name><photo>+ pic + </photo></pic>)MyXml Save( c:\MyPhoto xml )Label Text = 文件被保存到了 + Microsoft VisualBasic ChrW( ) + c:\MyPhoto xml End SubPrivate Sub Button _Click(ByVal sender As System Object ByVal e As System EventArgs) _Handles Button ClickDim openFileDialog As New OpenFileDialog()openFileDialog InitialDirectory = c:\ openFileDialog Filter = PNG(* png)|* png|Gif(* gif)|* gif|Jpg(* jpg)|* jpg|所有图象文件(* *)|* * openFileDialog FilterIndex = openFileDialog RestoreDirectory = TrueIf openFileDialog ShowDialog() = DialogResult OK ThenMyFile = openFileDialog FileName()MyFileExt = MyFile Substring(MyFile LastIndexOf( ) + )End IfEnd SubPublic Function GetImageType(ByVal str As String) As System Drawing Imaging ImageFormatSelect Case str ToLower()Case jpg Return System Drawing Imaging ImageFormat JpegCase gif Return System Drawing Imaging ImageFormat GifCase tiff Return System Drawing Imaging ImageFormat Tiff()Case icon Return System Drawing Imaging ImageFormat IconCase image/png Return System Drawing Imaging ImageFormat PngCase ElseReturn System Drawing Imaging ImageFormat MemoryBmpEnd SelectEnd FunctionPrivate Sub Form _Closing(ByVal sender As Object ByVal e As System ComponentModel CancelEventArgs) _Handles MyBase ClosingSystem Diagnostics Process Start( IExplore exe )End SubEnd Class lishixinzhi/Article/program/net/201311/11970

          1. 读取图片和标注后的xml文件,将标注信息写到txt文件中。生成的txt文件在txt文件夹下面,可以直接用于yolo3等目标检测算法的训练。

            2. txt文件包含图片的路径,标注框的位置和大小,以及标注的类别。

            3. 分割标注的图片,可以用于行人属性识别。分割的图片保存在segmentation文件夹下。

           1. 需要将数据集放在dataset路径下。

            2. Annotations存放的是xml文件,JPEGImages存放的是图片。

修改:需要针对需要进行适当的修改。下面进行说明:

第一:

class_tab={

"human":1  ##这个是类别,如果有多个类别,可以添加多条

}

第二:

params={"xml_prefix":"./dataset/Annotations/", ##这个是xml源文件的路径前缀,注意末尾要有“/”

        "img_prefix":"./dataset/JPEGImages/",##这个是图片源文件的路径前缀,注意末尾要有“/”

        "seg_prefix":"./segmentation/",##这个是分割后图片存放的位置前缀,注意末尾要有“/”

      }

第三:

f = open('手祥./txt/train.txt','a')##这个是生成的txt文件的路径。

import sys

#sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')

import cv2

import os

from readxml import *

class_tab={

"humanimport sys

#sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')

import cv2

import os

from readxml import *

class_tab={

"human":1

}

params={"xml_prefix":"./dataset/Annotations/",

        "img_prefix":"./dataset/JPEGImages/",

        "seg_prefix":"./segmentation/",

      }

def write_line(f, img_path, boxes):

    f.write("%s "%(img_path))

    for box in boxes:

      f.write(str(box['cls'])+",")

      f.write(str(box['xmin']+","))

      f.write(str(box['ymin']+","))

      f.write(str(box['xmax']+","))

      f.write(str(box['ymax']))

      f.write(" ")

    f.write("\n")

    f.flush()

def segment(img_path, imgname, boxes):

    img=cv2.imread(img_path, cv2.IMREAD_COLOR)

    cnt=0

    for box in boxes:

          seg=img[int(box['ymin']):int(box["ymax"]), int(box["xmin"]):int(box["xmax"]),:]

          cv2.imwrite(params["seg_prefix"]+imgname+"_"+str(cnt)+".jpg", seg)

          cnt=cnt+1

def main():

    f = open('./txt/train.txt','a')

 毕薯滚   img_list=os.listdir(params["img_prefix"])

    for il in img_list:

        img_path=params["img_prefix"]+il

        tokens=il.split(".")

        xml_path=params["xml_prefix"]+tokens[0]+"手余.xml"

        if os.path.isfile(img_path)==False:

            raise ValueError("%s does not exits!"%img_path)

        else:

            print("reading:", img_path)

            boxes=xml_reader(xml_path, class_tab)

            write_line(f,img_path,boxes)

            segment(img_path, tokens[0], boxes)

    f.close()

if __name__ == '__main__':

    main()

":1

}

params={"xml_prefix":"./dataset/Annotations/",

        "img_prefix":"./dataset/JPEGImages/",

        "seg_prefix":"./segmentation/",

      }

def write_line(f, img_path, boxes):

    f.write("%s "%(img_path))

    for box in boxes:

      f.write(str(box['cls'])+",")

      f.write(str(box['xmin']+","))

      f.write(str(box['ymin']+","))

      f.write(str(box['xmax']+","))

      f.write(str(box['ymax']))

      f.write(" ")

    f.write("\n")

    f.flush()

def segment(img_path, imgname, boxes):

    img=cv2.imread(img_path, cv2.IMREAD_COLOR)

    cnt=0

    for box in boxes:

          seg=img[int(box['ymin']):int(box["ymax"]), int(box["xmin"]):int(box["xmax"]),:]

          cv2.imwrite(params["seg_prefix"]+imgname+"_"+str(cnt)+".jpg", seg)

          cnt=cnt+1

def main():

    f = open('./txt/train.txt','a')

    img_list=os.listdir(params["img_prefix"])

    for il in img_list:

        img_path=params["img_prefix"]+il

        tokens=il.split(".")

        xml_path=params["xml_prefix"]+tokens[0]+".xml"

        if os.path.isfile(img_path)==False:

            raise ValueError("%s does not exits!"%img_path)

        else:

            print("reading:", img_path)

            boxes=xml_reader(xml_path, class_tab)

            write_line(f,img_path,boxes)

            segment(img_path, tokens[0], boxes)

    f.close()

if __name__ == '__main__':

    main()

from xml.dom.minidom import Document

import xml.etree.ElementTree as ET

def xml_reader(fname, cls_tab):###, classes_merge_list,classes_merged_name):

    in_file = open(fname)

    tree=ET.parse(in_file)

    root = tree.getroot()

    boxes=[]

    for item in root.iter('item'):

        cls = item.find('name').text

        if cls in cls_tab:

            bndbox = item.find('bndbox')

            b={

                "xmin": str(int(bndbox.find('xmin').text)),

                "ymin": str(int(bndbox.find('ymin').text)),

                "xmax": str(int(bndbox.find('xmax').text)),

                "ymax": str(int(bndbox.find('ymax').text)),

                "cls": cls_tab[cls]

                }

            boxes.append(b)

        else:

            continue

    return boxes

if __name__ == '__main__':

  cls_tab={"human":1}

  fname="/home/ta/Downloads/liqiming_label/dataset/Annotations/sa341.xml"

  box=xml_reader(fname, cls_tab)

  print(box)

#(转)将自己的图片转换为xml格式,代码实现:

using System

using System.Drawing

using System.Collections

using System.ComponentModel

using System.Windows.Forms

using System.Data

using System.Xml

using System.IO

using System.Drawing.Imaging

namespace xmlfile

{

/// <summary>厅哗

/// aboatfile 的摘要说扮悉行明。

/// </summary>

public class xmlfile

{

public xmlfile()

{

//

// TODO: 在此处添加构造函数逻辑

//

}

//找开一幅XML图片(XmlTextReader)

public Image openxmlfile(string xmlfilepath)

{

XmlTextReader readxml=new XmlTextReader(xmlfilepath)

int len=64*1024

byte[] bytebmp=new byte [len]

while (readxml.Read())

{

if (readxml.NodeType==XmlNodeType.Element)

{

if (readxml.LocalName.Equals("image"))

{

readxml.ReadBase64(bytebmp,0,len)

}

}

}

readxml.Close()

readxml=null

FileStream streamfile=File.OpenWrite(@"陆简C:Documents and SettingsAdministratorLocal SettingsTempa.bmp")

streamfile.Write(bytebmp,0,bytebmp.Length)

streamfile.Close()

streamfile=null

Image img

img=System.Drawing.Bitmap.FromFile(@"C:Documents and SettingsAdministratorLocal SettingsTempa.bmp")

return img

}

//保存一幅XML图片(XmlTextWriter)

public void savexmlfile(string xmlname)

{

FileStream fs=new FileStream(@"C:a.bmp",FileMode.Open)

string time=DateTime.Now.ToLongDateString()

int len=4029

int readByte=0

byte[] imgdata = new byte[len]

XmlTextWriter xw=new XmlTextWriter(xmlname,System.Text.Encoding.UTF8)

xw.WriteStartDocument()

xw.WriteComment("XML图片,用base64储存创建于"+time)

xw.WriteStartElement("image")

BinaryReader br = new BinaryReader(fs)

do

{

readByte=br.Read(imgdata, 0, len)

xw.WriteBase64(imgdata, 0, readByte)

}

while (len <= readByte )

xw.WriteEndElement()

xw.WriteEndDocument()

fs.Close()

xw.Flush()

xw.Close()

File.Delete(@"C:a.bmp")

}

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12267516.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-24
下一篇 2023-05-24

发表评论

登录后才能评论

评论列表(0条)

保存