先说说处理图片有三种方式
一、matplotlib
二、PIL
三、opencv
法一:
import cv2
img = cv2.imread("F:/mytest/1.MNIST/path/to/one.jpg")
cv2.imshow("img", img)
cv2.waitKey(0)
img_gray = cv2.cvtColor(img , cv2.COLOR_RGB2GRAY)#数组
print(img_gray.shape)
img = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)#元组
print(img)
法二:cv2
from PIL import Image
import matplotlib.pyplot as plt
# img = Image.open("F:/mytest/1.MNIST/path/to/one.jpg")
img = Image.open("F:/mytest/2.cat_dog/test/test/3.jpg")
# 模式L”为灰色图像,它的每个像素用8个bit表示,0表示黑,255表示白,其他数字表示不同的灰度
img = img.convert("L")
# plt.imshow(img)
# plt.show()
table = []
threshold = 120 # 自定义灰度界限,大于这个值为黑色,小于这个值为白色
for i in range(256):
if i >=threshold:
table.append(1)
else:
table.append(0)
img = img.point(table, "1")
plt.imshow(img)
plt.show()
再者或者:
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
img = np.array(Image.open('F:/mytest/2.cat_dog/test/test/2.jpg').convert('L'))
rows,cols=img.shape
for i in range(rows):
for j in range(cols):
if (img[i,j]<=128):
img[i,j]=0
else:
img[i,j]=1
plt.imshow(img)
plt.show()