感谢您阅读我的问题。
我是 python 新手,对 scipy 感兴趣。我试图弄清楚如何将浣熊的图像(在 scipy 杂项中)转换为二进制图像(黑色,白色)。scipy-lecture 教程中没有讲授这一点。
到目前为止,这是我的代码:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy import misc #here is how you get the racoon image
face = misc.face()
image = misc.face(gray=True)
plt.imshow(image, cmap=plt.cm.gray)
print image.shape
def binary_racoon(image, lowerthreshold, upperthreshold):
img = image.copy()
shape = np.shape(img)
for i in range(shape[1]):
for j in range(shape[0]):
if img[i,j] < lowerthreshold and img[i,j] > upperthreshold:
#then assign black to the pixel
else:
#then assign white to the pixel
return img
convertedpicture = binary_racoon(image, 80, 100)
plt.imshow(convertedpicture, cmap=plt.cm.gist_gray)
Run Code Online (Sandbox Code Playgroud)
我见过其他人使用 OpenCV 制作图片二进制文件,但我想知道如何通过循环像素来做到这一点?我不知道上限和下限应该给什么值,所以我猜测是80和100。还有没有办法确定这个?
你想太多了:
def to_binary(img, lower, upper):
return (lower < img) & (img < upper)
Run Code Online (Sandbox Code Playgroud)
在 中numpy,比较运算符按元素应用于整个数组。请注意,您必须使用&而不是and组合布尔值,因为 python 不允许numpy重载and