- 主要列出一些cv模块的实际应用代码,不做详细的解释
常用功能
彩色图像的边缘检测
import cv2
img = cv2.imread("1.PNG")
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray_img, 100, 200)
cv2.imwrite("edges2.jpg", edges)
图像读取和显示
import cv2
img = cv2.imread('2.png')
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
图像裁剪
import cv2
img = cv2.imread('2.png')
crop_img = img[100:200,100:200]
cv2.imshow('image',crop_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
图像模糊
import cv2
img = cv2.imread('2.png')
blur_img = cv2.GaussianBlur(img, (5, 5), 10)
cv2.imshow('image', blur_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
图像旋转
import cv2
image = cv2.imread("0.jpg")
(h, w) = image.shape[:2]
center = (w//2,h//2)
angle = 45
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(image, M, (w, h))
cv2.imshow("Rotated Image", rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()
图像缩放
import cv2
image = cv2.imread("0.jpg")
scale = 0.5
resized = cv2.resize(image, None, fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR) # 缩放图像
cv2.imshow("Resized Image", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()
scale = 2
resized = cv2.resize(image, None, fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR) # 缩放图像
cv2.imshow("Resized Image", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()
图像按边缘提取分割
import cv2
image = cv2.imread("0.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
(x, y, w, h) = cv2.boundingRect(contour)
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow("Segmented Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite("3.jpg", image)
寻找目标
import cv2
target_img = cv2.imread('1.jpg')
shoot_img = cv2.imread('0.jpg')
target_gray = cv2.cvtColor(target_img, cv2.COLOR_BGR2GRAY)
shoot_gray = cv2.cvtColor(shoot_img, cv2.COLOR_BGR2GRAY)
target_height, target_width = target_gray.shape[:2]
res = cv2.matchTemplate(shoot_gray, target_gray, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
#print("locate", max_loc)
top_left = max_loc
bottom_right = (top_left[0] + target_width, top_left[1] + target_height)
cv2.rectangle(shoot_img,top_left, bottom_right, (0, 0, 255), 2)
cv2.imshow('detected', shoot_img)
cv2.waitKey(0)
cv2.imwrite("detected.jpg",shoot_img)