Я работал над обработкой изображений и заметил нечто странное. Я взял информацию, пройдя по картинке и просто записав ее в текстовый файл. Даже без добавления пробелов или символов (без добавления новой строки и, в конце концов, я просто использовал оттенки серого вместо цвета). В то время как каждое из моих изменений обрезало размер изображения, окончательный текст все еще больше исходного изображения (даже после сжатия). Я даже реализовал карту для аппроксимации диапазонов буквами, поэтому вместо 3-х цифр (значения rgb) я использую один символ для диапазона (k-> 220,230; программа предполагает, что все k = 225). Почему файлы изображений меньше, чем мои текстовые файлы, даже после оттенков серого и сжатия?
def convertToText(img):
"""
Send the img information into a text file.
@return:(row,col) of image
"""
load=cv2.imread(img)
height, width, layers = load.shape
text=""
#print(height,width, layers)
file1=open(r"C:\Users\Devansh\Desktop\Projects\img\test2.txt","w+")
x=list()
sPixel=list()
for i in range(height):
for j in range(width):
pixel=load[i,j]
sPixel.append( int(str(pixel[0])+str(pixel[1])+str(pixel[2])) )
#text=text+(encode(str(pixel[0]))+encode(str(pixel[1]))+encode(str(pixel[2]))) #text
grayed=grayScale(pixel)
x.append([0,grayed])
#print("Fitting:",x,sPixel)
text=text+ str( encodeGray(grayed))
#file1.write('\n')
clf.fit(x,sPixel)
file1.write(text)
return (height,width)
def convertToImg(height,width):
file1=open(r"C:\Users\Devansh\Desktop\Projects\img\test2.txt")
blank_image = np.zeros((height,width,3), np.uint8)
i=0 #height index
j=0 #width index
colors=list(file1.read())
for index in range(0,len(colors),1):
#TODO: work on the stupid ungraying
#print("Color:",colors[index])
x=[[0,decode(colors[index])]]
#prediction=(clf.predict(x))
if(prediction==0):
blank_image[i][j]=[0,0,0]
else:
predictionS=str(prediction)
#index=
pixelAvg=average(predictionS)
blank_image[i][j]=[int(pixelAvg[0]),int(pixelAvg[1]),int(pixelAvg[2])]
#print("Pixel: ",pixelAvg)
blank_image[i][j]=[int(decode(colors[index])),int(decode(colors[index+1])),int(decode(colors[index+2]))]
if ( j<width-1 ):
j+=1
else:
j=0
i+=1
cv2.imshow("Get Wrecked Shree", blank_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
step=20
stepGrey=0.05
colorMap=dict()
chars=list(ascii_uppercase)
def createMap():
i=0
for middle in range (0,256,step):
colorMap[chars[i]]=middle
i+=1
#print(colorMap)
return colorMap
def createGreyMap():
for middle in range (21):
colorMap[chars[middle]]=float(middle/20)
#print(colorMap)
return colorMap
def encode(color):
"""
Encode the pixels color into the map
"""
color=int(color)
colorMap=createMap() #get the mapping for pixel value to letter
alpha=color//step #the alphabet corresponding to the number
return(str(list(colorMap.keys())[alpha]))
def encodeGray(grayed):
"""
Take grayscale value and map it to our charset
"""
colorMap=createGreyMap()
alpha=int(grayed/stepGrey) #the alphabet corresponding to the number
return(str(list(colorMap.keys())[alpha]))
def decode(char):
"""
Return color value corresponding to the char
"""
char=str(char).capitalize()
colorMap=createMap()
#print(colorMap['A'])
return(int(colorMap[char]))
def decodeGrey(char):
"""
Return color value corresponding to the char
"""
char=str(char).capitalize()
colorMap=createGreyMap()
#print(colorMap['A'])
return( ungray(colorMap[char]) )
def grayScale(n):
"""
Take pixel and returns the mathematical grayscaled value
"""
r,g,b =n[0]/255, n[1]/255, n[2]/255 #fractional values
linearCoeff= 0.2126 *r + 0.7152*g + 0.0722*b #math and explaination in documentation
grayed=0
if(linearCoeff<=0.0031308): # implementing the gamma adjustement
grayed= 12.92*linearCoeff
else:
grayed=1.055* pow(linearCoeff,1/2.4) - 0.055 #non linear factor
#return grayed
return grayed
def ungray(n):
"""
Take grayscaled n and return ungrayed pixel color
"""
#TODO: find the actual probability distribution.
return int(n*255)
Могут быть некоторые ошибки при выполнении этого, потому что я попытался добавить некоторое машинное обучение для проекта но основные функции c должны работать.