相關庫安裝指導:
這里我們需要 opencv_python,numpy,matplotlib庫,另外我用的是python3.6.1版本。
一般庫大家都是用pip install命令安裝的,不過不知道為啥這里的opencv_python庫總是抽風,就是安裝不了(起碼我周圍都是這樣)。
所以以上哪個庫如果下載不動啥的可以去這里下載:海克斯科技傳送門
如果不知道下載哪個版本可以通過
import pip; print(pip.pep425tags.get_supported())這條命令來查看
你的python所支持的whl 文件類型(否則容易發生:
* is not a supported wheel on this platform錯誤)
如圖:
之后可以通過“import”對應的庫來驗證是否安裝成功。
python + opencv實現提取png圖像的像素信息並存儲到txt文件中代碼:
注意這里的文件路徑要根據個人情況修改。
import cv2
import numpy
import pylab
import matplotlib.pyplot as plt
imgfile = input("請輸入圖片名:")
txtfile = input("請輸入存儲文本文件名:")
img = cv2.imread("C:/Users/Jake/Desktop/test01/"+imgfile,cv2.IMREAD_GRAYSCALE)
print("圖像的形狀,返回一個圖像的(行數,列數,通道數):",img.shape)
print("圖像的像素數目:",img.size)
print("圖像的數據類型:",img.dtype)
#----------------------------------------------------------------------------
"""
In windows the COLOR->GRAYSCALE: Y = 0.299R+0.587G+0.114B 測試是否三個通道的值是相同的。
某些圖像三通道值相同,可以直接讀灰度圖來代替讀單一通道。
"""
# sum = 0
# ans = 0
# for i in range(562):
# for j in range(715):
# if not(img[i][j][0] == img[i][j][1] and img[i][j][1] == img[i][j][2]):
# sum += 1
# else:
# ans += 1
# print(ans)
# print(sum)
#-----------------------------------------------------------------------------
"""
將圖片數據寫入txt文件
格式:
基礎信息
行號:
像素值
行號:
像素值
......
"""
fname = open("C:/Users/Jake/Desktop/test01/"+txtfile,'w')
fname.write("圖像的形狀,返回一個圖像的(行數,列數,通道數):"+str(img.shape)+'\n')#----1
fname.write("圖像的像素數目:"+str(img.size)+'\n')#----2
fname.write("圖像的數據類型:"+str(img.dtype)+'\n')#----3
Xlenth = img.shape[1]#圖片列數
Ylenth = img.shape[0]#圖片行數
a = 1#----4
for i in range(Ylenth):
fname.write(str(a) + ':'+'\n')#----5
for j in range(Xlenth):
fname.write(str(img[i][j])+' ')
a += 1#----6
fname.write('\n')
fname.close()
#---------------------------------------------------------------------------
"""
將txt文件中的數據讀取進blist
並顯示為"test"圖片框進行測試。
注意進行測試前需要注釋掉數據寫入模塊
中標記的六行代碼,要不然讀取會出錯誤。
"""
# blist = []
# split_char = ' '
# with open('C:/Users/Jake/Desktop/test01/'+txtfile, 'r') as bf:
# blist = [b.strip().split(split_char) for b in bf]
#
##從txt文件讀入進來的值類型是char需要轉換為int
# for i in range(Ylenth):
# for j in range(Xlenth):
# blist[i][j] = int(blist[i][j])
#
# tlist = numpy.array(blist)
# plt.figure()
# plt.imshow(tlist)
# plt.axis('off') # 不顯示坐標軸
# pylab.show()
#------------------------------------------------------------------------------
"""
將圖片顯示在'image'圖片框
"""
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
#----------------------------------------------------------------------
