【12】python数据写入csv和txt中

【1】通常在处理数据时需要将结果保存到文件中,一般常用的为excel和txt文件中。

【2】保存csv具体代码

cvs写入的是列表,因此需要将表格的每一行转换为列表然后写入,encoding='utf-8-sig'如果不设置为此格式,打开csv文件中文会乱码。

if __name__=="__main__":
	'''
	以下方法将结果写入csv文档中
	'''
	openpath="D:/pythonprocedure/ConcludeArea/Dataset2/"
	images,name=GetImg(openpath)
	#打开文件 w表示只写,没有文件创建一个新的文件,
	# encoding='utf-8-sig':写入的格式
	#newline='' "":换行
	file = open('result2.csv','w',encoding='utf-8-sig',newline='' "")
	test1=["图片名"," 细胞膜的面积"," 细胞核的面积"," 细胞核占比"]
	#实例化对象
	csv_writer = csv.writer(file)
	#写入数据
	csv_writer.writerow(test1)
	#建立一个列表用于写入数据
	lista=[]
	for index in range(len(images)):
		inputImg=images[index]
		GrayImg=cv2.cvtColor(inputImg ,cv2.COLOR_BGR2GRAY)
		area1,area2,proportion=lowGravity(GrayImg)
		test="Dataset1-"+str(name[index])
		lista.append(test)
		lista.append(area1)
		lista.append(area2)
		lista.append(proportion)
		#写入数据
		csv_writer.writerow(lista)
		#清除列表,不清除会累加
		lista.clear()
	file.close()
	print("end!")

【3】txt格式保存

txt格式只能保存字符串,而不能保存其他类型,因此需要将数据转换为字符串后在保存到结果中。

# -*- coding: utf-8 -*-
# @Time    : 2020/6/28 13:23
# @Author  : song
# @File    : writeintxt.py
# @Software: PyCharm


from  Concludearea import*

if __name__=="__main__":
	'''
	以下方法将结果写入csv文档中
	'''
	openpath="D:/pythonprocedure/ConcludeArea/Dataset2/"
	images,name=GetImg(openpath)

	file=open("result.txt","w")
	test1="图片名"+" 细胞膜的面积"+" 细胞核的面积"+" 细胞核占比"
	file.write(test1+'\n')

	for index in range(len(images)):
		inputImg=images[index]
		GrayImg=cv2.cvtColor(inputImg ,cv2.COLOR_BGR2GRAY)
		area1,area2,proportion=lowGravity(GrayImg)
		test2="Dataset1-"+str(name[index])+" "+str(area1)+" "+str(area2)+" "+str(proportion)

		#写入数据
		file.write(test2+'\n')

	file.close()
	print("end!")

【4】完整代码

# -*- coding: utf-8 -*-
"""
author:song
"""
import  cv2
import  numpy as np
import os
import csv

def lowGravity(inputImg):
	imgInfo=inputImg.shape
	height=imgInfo[0]
	width=imgInfo[1]
	Cellmembrabcelist=[]
	Cellnucleslist=[]
	Cellmembrabce = np.zeros((height,width,1), np.uint8)
	Cellnucles= np.zeros((height,width,1), np.uint8)
	for cols in range(height):
		for rows in range(width):
			if inputImg[cols,rows]>100 and inputImg[cols,rows]<200:
				Cellmembrabce[cols,rows]=255
				Cellmembrabcelist.append(1)
			if inputImg[cols,rows]>220 :
				Cellnucles[cols,rows]=255
				Cellnucleslist.append(1)
	#计算面积
	cv2.imwrite("Cellmembrabce.png",Cellmembrabce)
	cv2.imwrite("Cellnucle.png",Cellnucles)
	area1=len(Cellmembrabcelist)
	area2=len(Cellnucleslist)
	proportion=area2/(area1+area2)
	return area1,area2,proportion

#载入图片,处理后保存到一个列表中
def GetImg(open_path):
	patch=[]
	name=[]
	for dir_image in os.listdir(open_path): # os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表
		full_path = os.path.abspath(os.path.join(open_path,dir_image))
		if dir_image.endswith('.png'):
			image = cv2.imread(full_path)
			(filepath, filename) = os.path.split(full_path)
			nameall = os.path.splitext(filename)[0]
			patch.append(image)
			name.append(nameall)
	return  patch,name


if __name__=="__main__":
	'''
	以下方法将结果写入csv文档中
	'''
	openpath="D:/pythonprocedure/ConcludeArea/Dataset2/"
	images,name=GetImg(openpath)
	#打开文件 w表示只写,没有文件创建一个新的文件,
	# encoding='utf-8-sig':写入的格式
	#newline='' "":换行
	file = open('result2.csv','w',encoding='utf-8-sig',newline='' "")
	test1=["图片名"," 细胞膜的面积"," 细胞核的面积"," 细胞核占比"]
	#实例化对象
	csv_writer = csv.writer(file)
	#写入数据
	csv_writer.writerow(test1)
	#建立一个列表用于写入数据
	lista=[]
	for index in range(len(images)):
		inputImg=images[index]
		GrayImg=cv2.cvtColor(inputImg ,cv2.COLOR_BGR2GRAY)
		area1,area2,proportion=lowGravity(GrayImg)
		test="Dataset1-"+str(name[index])
		lista.append(test)
		lista.append(area1)
		lista.append(area2)
		lista.append(proportion)
		#写入数据
		csv_writer.writerow(lista)
		#清除列表,不清除会累加
		lista.clear()
	file.close()
	print("end!")



【5】结果展示

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值