程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python implements image to TXT storage, and then from txt to image, including gray and color output

編輯:Python

**
The code can be used directly , Just change your path

Color picture display :

# -*- coding:utf-8 -*-
import cv2
import numpy
import numpy as np
import pylab
import PIL.Image as Image
import matplotlib.pyplot as plt
imgfile = input(" Please enter the picture name :")
txtfile = input(" Please enter the name of the storage text file :")
''' cv2.imread() Used to read picture files , It should be noted that the order of the three channels is BGR, The latter needs to be transformed into RGB Sequential output imread Function has two arguments , The first parameter is the image path , The second parameter represents the form of reading the picture , There are three kinds of : cv2.IMREAD_COLOR: Load color picture , This is the default parameter , You can write directly 1. cv2.IMREAD_GRAYSCALE: Load image in grayscale mode , You can write directly 0. cv2.IMREAD_UNCHANGED: Include alpha, You can write directly -1 '''
img = cv2.imread("G:\python\image_array\images" + "\\" + imgfile + ".png", cv2.IMREAD_COLOR)
print(" The shape of the image , Returns the of an image ( Row number , Number of columns , The channel number ):", img.shape)
print(" The number of pixels in the image :", img.size)
print(" The data type of the image :", img.dtype)
print("img:",img[0][0][1]) # Check whether the reading is normal 
# ----------------------------------------------------------------------------
''' In windows the COLOR->GRAYSCALE: Y = 0.299R+0.587G+0.114B Test whether the values of the three channels are the same . Some images have the same three channel values , Instead of reading a single channel, you can read the grayscale image directly . """ sum = 0 ans = 0 for i in range(328):1 for j in range(640): 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) '''
# -----------------------------------------------------------------------------
fname = open("G:\python\image_array\images" + "\\" + txtfile, 'w')
Xlenth = img.shape[1] # Number of picture Columns 
Ylenth = img.shape[0] # Number of picture lines 
k = 3 # Every pixel RGB The value of three channels 
for i in range(Ylenth):
for j in range(Xlenth):
for h in range(k):
fname.write(str(img[i][j][h]) + ' ')
fname.close()
# ---------------------------------------------------------------------------
''' take txt The data in the file is read into blist And it's shown as "test" Test the picture box . '''
# -----------------------------------------------------------------------------
blist = []
split_char = ' ' # The meaning of spaces , Details can be viewed strip And spilt Usage of 
with open("G:\python\image_array\images" + "\\" + txtfile, 'r') as bf:
blist = [b.strip().split(split_char) for b in bf]
# Here are the questions that took a day to find , Read txt Of documents blist Finally, a two-dimensional ,blist[0][ Image maximum -1]
# array_len = The number of pixels in the image *RGB Three channels (3)
array_len = Ylenth * Xlenth * 3
print("blist:", (blist[0][array_len - 1]))
# from txt The value type read in from the file is char Need to be converted to int
for i in range(1):
for j in range(array_len - 1):
blist[i][j] = int(blist[i][j])
# Extract the required shaping data , Then divide it into three-dimensional arrays new_blist, This makes it easy to separate the channels 
new_blist = np.zeros((img.shape)).astype("uint8")
i = 0
for j in range(Ylenth):
for k in range(Xlenth):
for l in range(3):
new_blist[j][k][l] = blist[0][i]
i = i + 1
if (i >= array_len):
break
# Verification test , And write img Of txt Compare the data 
print("new_blist:", (new_blist[0][0][1]))
# because ov The way to store images is BGR The order , So turn it into RGB The correct image can only be obtained by outputting 
B = new_blist[:, :, 0]
G = new_blist[:, :, 1]
R = new_blist[:, :, 2]
src_new = np.zeros((img.shape)).astype("uint8")
src_new[:, :, 0] = R
src_new[:, :, 1] = G
src_new[:, :, 2] = B
# This sentence is optional , Remove the words below tlist become src_new that will do , For the purpose of creating multidimensional arrays 
tlist = numpy.array(src_new)
# The plot 
plt.figure()
plt.imshow(tlist)
plt.axis('on') # No axes are displayed 
pylab.show()
# ------------------------------------------------------------------------------
# The original picture is shown in img box 
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Grayscale picture display :


# -*- coding:utf-8 -*-
import cv2
import numpy
import pylab
import PIL.Image as Image
import matplotlib.pyplot as plt
from cv2 import COLOR_RGB2GRAY
imgfile = input(" Please enter the picture name :")
txtfile = input(" Please enter the name of the storage text file :")
''' cv2.imread() Used to read picture files imread Function has two arguments , The first parameter is the image path , The second parameter represents the form of reading the picture , There are three kinds of : cv2.IMREAD_COLOR: Load color picture , This is the default parameter , You can write directly 1. cv2.IMREAD_GRAYSCALE: Load image in grayscale mode , You can write directly 0. cv2.IMREAD_UNCHANGED: Include alpha, You can write directly -1 '''
img = cv2.imread("G:\python\image_array\images" + "\\" + imgfile + ".png",cv2.IMREAD_GRAYSCALE)
# img = cv2.cvtColor(img, COLOR_RGB2GRAY)
print(" The shape of the image , Returns the of an image ( Row number , Number of columns , The channel number ):", img.shape)
print(" The number of pixels in the image :", img.size)
print(" The data type of the image :", img.dtype)
fname = open("G:\python\image_array\images" + "\\" + txtfile, 'w')
Xlenth = img.shape[1] # Number of picture Columns 
Ylenth = img.shape[0] # Number of picture lines 
for i in range(Ylenth):
for j in range(Xlenth):
fname.write(str(img[i][j]) + ' ')
fname.write('\n')
fname.close()
# ---------------------------------------------------------------------------
blist = []
split_char = ' '
with open("G:\python\image_array\images" + "\\" + txtfile, 'r') as bf:
blist = [b.strip().split(split_char) for b in bf]
# from txt The value type read in from the file is char Need to be converted to 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.title("gray")
plt.imshow(tlist, cmap='gray')
plt.axis('on') # No axes are displayed 
pylab.show()
# ------------------------------------------------------------------------------
# """
# Display the picture in 'image' Picture box 
# """
#
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

About numpy The explanation of :https://blog.csdn.net/fu6543210/article/details/83240024
About plt.imshow():https://blog.csdn.net/weixin_44690866/article/details/111877574
Thought source :https://www.cnblogs.com/vocaloid01/p/9514142.html

Your own food is better than one , I hope you can tell me in the comments section if you have any suggestions , Just beginning to learn .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved