圖片尺寸要自己修改。
看起來好像沒啥意思,不知道下一步能干什么,先卷了再說。由於weights是隨機生成的(tf.random_normal作用:用於從服從指定正太分布的數值中取出隨機數),所以每次卷積后的圖像會不一樣。
代碼:
def func19(img_path): # 讀取圖片,矩陣化,轉換為張量 img_data = cv2.imread(img_path) img_data = tf.constant(img_data, dtype=tf.float32) print(img_data.shape) # 將張量轉化為4維 img_data = tf.reshape(img_data, shape=[1, 454, 700, 3]) print(img_data.shape) # 權重(也叫filter、過濾器) weights = tf.Variable(tf.random_normal(shape=[2, 2, 3, 3] , dtype=tf.float32)) print(weights.shape) # 卷積 conv = tf.nn.conv2d(img_data, weights, strides=[1, 3, 3, 1], padding='SAME') print(conv.shape) img_conv = tf.reshape(conv, shape=[152, 234, 3]) print(img_conv.shape) img_conv = tf.nn.relu(img_conv) with tf.Session() as sess: # 全局初始化 sess.run(tf.global_variables_initializer()) img_conv = sess.run(img_conv) plt.title('conv') plt.imshow(img_conv) plt.show() return if __name__ == '__main__': img_path = r'你的圖片路徑' func19(img_path)
原圖(尺寸:(454, 700, 3)):
效果(尺寸: (152, 234, 3) ):