Python cv模块实际应用

这篇文章展示了OpenCV库在Python中进行图像处理的一些基本操作,包括彩色图像的边缘检测、图像读取和显示、图像裁剪、模糊处理、旋转、缩放以及目标检测。通过实例代码,读者可以了解如何利用OpenCV进行图像分析和处理。
摘要由CSDN通过智能技术生成
  • 主要列出一些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)

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

River Chandler

谢谢,我会更努力学习工作的!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值