jez*_*ael 5 python replace numpy image python-imaging-library
我输入了带有隐藏文本的图像文件,问题是隐藏文本的像素差异非常小,有时只有 1px。我想更改像素以查看此文本。
因为从不使用类似的想法是将图像转换为 numpy 数组并用 dict 替换值:
from PIL import Image
import matplotlib
img = Image.open('4YtCA.jpg')
data = np.array( img, dtype='uint8' )
#print (data)
a = np.ravel(data)
u, c = np.unique(a, return_counts=True)
print (u)
[ 48 49 50 51 77 78 79 80 100 101 102 103 121 122 123 124 142 143
144 145 164 165 166 167 188 189 190 191 208 209 210 211 212 230 231 232
233 253 254 255]
#new values for replace
new = (u.reshape(-1, 4) / [1,2,3,4]).astype(int)
print (new)
[[ 48 24 16 12]
[ 77 39 26 20]
[100 50 34 25]
[121 61 41 31]
[142 71 48 36]
[164 82 55 41]
[188 94 63 47]
[208 104 70 52]
[212 115 77 58]
[233 126 84 63]]
Run Code Online (Sandbox Code Playgroud)
d = dict(zip(u, np.ravel(new)))
#print (d)
#/sf/answers/3280829751/
indexer = np.array([d.get(i, -1) for i in range(data.min(), data.max() + 1)])
out = indexer[(data - data.min())]
matplotlib.image.imsave('out.png', out.astype(np.uint8))
Run Code Online (Sandbox Code Playgroud)
我认为我的解决方案不好,因为最后一个值不是很好看。是否可以将像素更改为一些不同的颜色,如红色、绿色、紫色?或者用更好的方式改变合同?最好的办法是用一些聪明的方式改变每个像素,但不知道如何改变。
输入图像:
输出图像:
您可以尝试直方图均衡。现在我将在终端中使用ImageMagick来演示:
magick hidden.jpg -equalize -rotate -90 result.png
Run Code Online (Sandbox Code Playgroud)
或“本地自适应阈值” - 请参阅此处:
magick hidden.jpg -lat 50x50 -rotate -90 result.png
Run Code Online (Sandbox Code Playgroud)
如果您正在运行 v6 ImageMagick,请替换之前命令中的magick
with convert
。
这在 Python 中非常等效:
from PIL import Image
from skimage.filters import threshold_local
import numpy as np
# Open image in greyscale
im = Image.open('hidden.jpg').convert('L')
na = np.array(im)
# Local Adaptive Threshold
LAT = threshold_local(na, 49)
result = na > LAT
Image.fromarray((result*255).astype(np.uint8)).save('result.png')
Run Code Online (Sandbox Code Playgroud)
如果您真的,真的不想引入对 的新依赖skimage
,则可以使用 PIL 或 Numpy 生成图像的模糊副本,并从原始图像中减去模糊部分,然后对差异图像进行阈值处理。看起来像这样:
#!/usr/bin/env python3
from PIL import Image, ImageFilter
import numpy as np
# Open image in greyscale, and make heavily blurred copy
im = Image.open('hidden.jpg').convert('L')
blur = im.filter(ImageFilter.BoxBlur(25))
# Go to Numpy for maths!
na = np.array(im)
nb = np.array(blur)
# Local Adaptive Threshold
res = na >= nb
# Save
Image.fromarray((res*255).astype(np.uint8)).save('result.png')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
176 次 |
最近记录: |