Jinkey. ai/post/tech/l… The author of this article Jinkey (wechat public account Jinkey-love, official website Jinkey.ai) article allows non-tampering with the attribution of reprint, delete or modify this section of copyright information reprint, as infringement of intellectual property rights, we reserve the right to pursue your legal liability, hereby declare!

Dependent libraries

Requirements.txt is as follows

keras

numpy

pillow

Project directory structure





1.6.py is the script of this tutorial. Sample images to work with:




test.png

Image preprocessing

Img = image.open ('img/test.png') img = image.open ('img/test.png') Img_gray = img.convert("L") # Because keras requires the input shape of 2D convolution layer to be (width, height, number of channels), there is only one channel for gray value, Img_gray_array = Np.expand_dims (np.array(img_gray), axis=2) # imG_gray_array. shape = (64, 64, 1)Copy the code

Creating the convolution layer

Model = kr.sequential () # def jk_kernel(shape): Return np.expand_dims(np.expand_dims(kernel, axis=2), axis=2) # add(ker.layers.Conv2D(filters=1, kernel_size=3, kernel_initializer=jk_kernel, strides=1, padding='same', name='conv2d', Model.compile (Optimizer ='rmsprop', loss='categorical_crossentropy')Copy the code

Output the results of the middle layer

conv2d_layer_model = kr.Model(inputs=model.input,
                                     outputs=model.get_layer('conv2d').output)
conv2d_output = conv2d_layer_model.predict(np.expand_dims(img_gray_array, axis=0))
# conv2d_output.shape = (1, 64, 64, 1)
Copy the code

According to

Img_gray_array_squeeze = np.squeeze(conv2d_output) Image.fromarray(img_gray_array_squeeze).convert('RGB').save(fp='img/edge.png')Copy the code

The output edge detection result is:




edge.png