python xlwt 寫入數據到excel

聲明

  • xlwt是python中寫入到excel的庫
  • 僅支持寫入到xls文件
  • 支持最大寫入65535行,超過會報錯。此時建議使用openpyxl,詳見我的另一篇博客:python openpyxl 讀寫excel

具體步驟

  • 第一步,新建表格
  • 第二步,新建工作表sheet
  • 第三步,寫入數據,給定行列號和值
  • 第四步,保存表格
import cv2
import numpy as np
from xlwt import *

txtpath = r'a.txt'

# 新建表格
file = Workbook(encoding='utf-8')
# 新建工作表sheet
table = file.add_sheet('hwrgb')
# 寫入表頭
table.write(0, 0, 'height')
table.write(0, 1, 'width')
table.write(0, 2, 'channnel')
table.write(0, 3, 'red')
table.write(0, 4, 'green')
table.write(0, 5, 'blue')

num = 1

for line in open(txtpath):
    # 獲取圖片路徑並讀取
    line = line.strip()
    line_split = line.split(' ')
    image_path = line_split[0]
    img = cv2.imread(image_path, cv2.COLOR_BGR2RGB)
    
    # 獲取圖片均值和尺寸
    height, width, channnel = img.shape[0], img.shape[1], img.shape[2]
    img_mean = np.mean(img, axis=(0, 1))

    # 將尺寸和顏色信息寫入表格
    table.write(num, 0, height)
    table.write(num, 1, width)
    table.write(num, 2, channnel)
    table.write(num, 3, img_mean[0])
    table.write(num, 4, img_mean[1])
    table.write(num, 5, img_mean[2])

    num += 1

# 存儲表格到指定目錄
file.save('{}.xls'.format(r'D:\defect_segmentation\DataSet\hw_rgb'))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章