思路
图片->字符:
(1)下载下来的图片
(2)分析RGB值
(3)RGB值->字符表示(中间过程可转换形成灰度值,再对应字符)
学习提示
学习使用pilow库和argparse库的使用
pillow库:关于图像的库;argparse库:命令行参数相关库
参考链接
得到RGB值
import cv2
import numpy as np
img = cv2.imread("D:\\try_try\\dlAm2.jpg", 1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
for i in range(height):
for j in range(width):`在这里插入代码片`
(b, g, r) = img[i, j]
b = int(b)
g = int(g)
r = int(r)
gray = r*0.299 + g*0.587 + b*0.114
注意cv2.imread()路径中写法:
1.路径中不能含有中文
2.图片文件名字不能含有中文
3.绝对路径则必须是反双斜杠
4.如果图像文件太大也会使得cv2.imread()得到NoneType
除了利用cv2模块获取图像,还可使用pillow库中的Image的open函数打开图像文件,利用size函数得到宽高,再使用getpixel得到rgb值
将RGB值对应到字符上
my_string=list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
length=len(my_string)
swap=256/length
txt+=my_string[int(gray/swap)]
最初图像->结果图像
最初图像:
大概结果图像:
完整代码
import cv2
import numpy as np
img = cv2.imread("D:\\try_try\\dlAm2.jpg", 1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
dst = np.zeros([height, width], np.uint8)
my_string=list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
length=len(my_string)
swap=256/length
txt=""
for i in range(height):
for j in range(width):
(b, g, r) = img[i, j]
b = int(b)
g = int(g)
r = int(r)
gray = r*0.299 + g*0.587 + b*0.114
txt+=my_string[int(gray/swap)]
txt+='\n'
print(txt)
with open("output.txt",'w') as f:
f.write(txt)
"""
cv2.imshow('image', dst)
cv2.waitKey(0)
"""
"""
import cv2
img = cv2.imread("D:\\try_try\\dlAm.jpg",1)
imgInfo = img.shape
print(imgInfo)
"""