Today, Xiaobian will introduce to you 3 practical Python projects in the direction of computer vision that are full of dry goods. The main libraries used are:
- opencv-python
- numpy
- pillow
If you don't have these modules in your configured environment, you need to download and install them with the pip command first.
pip install opencv-python numpy pillow
edge detection
The basic idea of edge detection is to simplify the image information and use edge lines to represent the information carried by the image, and this time we are going to use the Canny edge detection operator. In Opencv, we need to call the cv.canny() method. ,code show as below
import cv2 as cv
import matplotlib.pyplot as plt
img = cv.imread('导入图像的路径',0)
edges = cv.Canny(img,100,200)
plt.subplot(121)
plt.imshow(img, cmap='gray')
.........
plt.show()
output
Turn photos into sketch style
The ultimate goal we want to achieve is to turn the photo into a sketch style. The general logic is to first turn the picture into a gray image and then invert it, and then blur it after inversion. The code is as follows
import cv2
img = cv2.imread("导入照片的路径")
## 将照片灰度化处理
gray_image = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
## 将灰度化的照片反转处理
inverted_gray_image = 255-gray_image
## 将反转的照片模糊化处理
blurred_inverted_gray_image = cv2.GaussianBlur(inverted_gray_image, (19,19),0)
## 再一次的进行反转
inverted_blurred_image = 255-blurred_inverted_gray_image
### 颜色减淡混合处理
sketck = cv2.divide(gray_image, inverted_blurred_image,scale= 256.0)
cv2.imshow("Original Image",img)
cv2.imshow("Pencil Sketch", sketck)
cv2.waitKey(0)
output
Judging the shape
Now we need to judge the outline of the figure in the picture, and the algorithm for identifying the outline is built-in in the opencv module, the code is as follows
import cv2
import numpy as np
from matplotlib import pyplot as plt
# 导入照片
img = cv2.imread('3.png')
# 将照片灰度化处理,当然要是您的照片已经是黑白的,就可以跳过这一步
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# setting threshold of the gray image
_, threshold = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# 识别轮廓的方法
contours, _ = cv2.findContours(
threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
i = 0
for contour in contours:
# cv2.approxPloyDP() function to approximate the shape
approx = cv2.approxPolyDP(contour, 0.01 * cv2.arcLength(contour, True), True)
# 找到图片的中心点
M = cv2.moments(contour)
if M['m00'] != 0.0:
x = int(M['m10'] / M['m00'])
y = int(M['m01'] / M['m00'])
# 将轮廓的名字放在各个图形的中央
if len(approx) == 3:
cv2.putText(img, 'Triangle', (x, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 0), 2)
elif len(approx) == 4:
.......
elif len(approx) == 5:
......
elif len(approx) == 6:
......
else:
......
# 将最后的图形呈现出来
cv2.imshow('shapes', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
output
Today's content is shared here, and the editor finally prepared a python spree for everyone [Jiajun Yang: 419693945] to help everyone learn better!