点击上方“小白学视觉”,选择加"星标"或“置顶”
重磅干货,第一时间送达
pip install ultralyticsimport urllib.requestimport cv2# Download the imageurl, filename = ("https://images.unsplash.com/photo-1634646493821-9fca74f85f59?w=600&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8Mzk0fHx1bmJsdXJyZWQlMjBwb3J0YWl0fGVufDB8fDB8fHww", "scene.jpg")urllib.request.urlretrieve(url, filename)# Load the input image using OpenCVimage = cv2.imread(filename)
import urllib.requestimport cv2from ultralytics import YOLOimport numpy as npdef segment_image(image, model):# Predict with the modelresults = model(filename) # predict on an image# Create an empty mask for segmentationsegmentation_mask = np.zeros_like(image, dtype=np.uint8)# Iterate over the resultsfor i, r in enumerate(results):# Iterate through the detected masksfor j, mask in enumerate(r.masks.xy):# Convert the class tensor to an integerclass_id = int(r.boxes.cls[j].item()) # Extract the class ID as an integer# Check if the detected class corresponds to 'person' (class ID 0)if class_id == 0:# Convert mask coordinates to an integer format for drawingmask = np.array(mask, dtype=np.int32)# Fill the segmentation mask with color (e.g., white for people)cv2.fillPoly(segmentation_mask, [mask], (255, 255, 255))return segmentation_mask# Download the imageurl, filename = ("https://images.unsplash.com/photo-1634646493821-9fca74f85f59?w=600&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8Mzk0fHx1bmJsdXJyZWQlMjBwb3J0YWl0fGVufDB8fDB8fHww", "scene.jpg")urllib.request.urlretrieve(url, filename)# Load the input image using OpenCVimage = cv2.imread(filename)# Load the modelmodel = YOLO("yolo11n-seg.pt") # load an official YOLO model# Generate the segmentation masksegmentation_mask = segment_image(image, model)# Visualize the segmentation mask before combining it with the original imagecv2.imwrite("mask.jpg", segmentation_mask)
import urllib.requestimport cv2from ultralytics import YOLOimport numpy as npdef segment_image(image, model):# Predict with the modelresults = model(filename) # predict on an image# Create an empty mask for segmentationsegmentation_mask = np.zeros_like(image, dtype=np.uint8)# Iterate over the resultsfor i, r in enumerate(results):# Iterate through the detected masksfor j, mask in enumerate(r.masks.xy):# Convert the class tensor to an integerclass_id = int(r.boxes.cls[j].item()) # Extract the class ID as an integer# Check if the detected class corresponds to 'person' (class ID 0)if class_id == 0:# Convert mask coordinates to an integer format for drawingmask = np.array(mask, dtype=np.int32)# Fill the segmentation mask with color (e.g., white for people)cv2.fillPoly(segmentation_mask, [mask], (255, 255, 255))return segmentation_maskdef apply_blur_using_mask(image, mask, blur_strength=(25, 25)):# Apply Gaussian blur to the entire imageblurred_image = cv2.GaussianBlur(image, blur_strength, 0)# Create an inverted mask where the background is white and the person is blackinverted_mask = cv2.bitwise_not(mask)# Use the mask to keep the person sharp and blur the backgroundbackground_blur = cv2.bitwise_and(blurred_image, blurred_image, mask=inverted_mask[:, :, 0])person_region = cv2.bitwise_and(image, image, mask=mask[:, :, 0])# Combine the sharp person region with the blurred backgroundfinal_image = cv2.add(person_region, background_blur)return final_image# Download the imageurl, filename = ("https://images.unsplash.com/photo-1634646493821-9fca74f85f59?w=600&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8Mzk0fHx1bmJsdXJyZWQlMjBwb3J0YWl0fGVufDB8fDB8fHww", "scene.jpg")urllib.request.urlretrieve(url, filename)# Load the input image using OpenCVimage = cv2.imread(filename)# Load the modelmodel = YOLO("yolo11n-seg.pt") # load an official YOLO model# Generate the segmentation masksegmentation_mask = segment_image(image, model)# Call the function to apply the blur and save the resultfinal_image = apply_blur_using_mask(image, segmentation_mask)# Visualize the segmentation mask before combining it with the original imagecv2.imwrite("mask.jpg", segmentation_mask)# Save the resultcv2.imwrite("blurred_image.jpg", final_image)# Optionally display the image (make sure you're running in a GUI environment)cv2.imshow("Blurred Image Result", final_image)cv2.waitKey(0)cv2.destroyAllWindows()
下载1:OpenCV-Contrib扩展模块中文版教程 在「小白学视觉」公众号后台回复:扩展模块中文教程,即可下载全网第一份OpenCV扩展模块教程中文版,涵盖扩展模块安装、SFM算法、立体视觉、目标跟踪、生物视觉、超分辨率处理等二十多章内容。 下载2:Python视觉实战项目52讲 在「小白学视觉」公众号后台回复:Python视觉实战项目,即可下载包括图像分割、口罩检测、车道线检测、车辆计数、添加眼线、车牌识别、字符识别、情绪检测、文本内容提取、面部识别等31个视觉实战项目,助力快速学校计算机视觉。 下载3:OpenCV实战项目20讲 在「小白学视觉」公众号后台回复:OpenCV实战项目20讲,即可下载含有20个基于OpenCV实现20个实战项目,实现OpenCV学习进阶。 交流群
欢迎加入公众号读者群一起和同行交流,目前有SLAM、三维视觉、传感器、自动驾驶、计算摄影、检测、分割、识别、医学影像、GAN、算法竞赛等微信群(以后会逐渐细分),请扫描下面微信号加群,备注:”昵称+学校/公司+研究方向“,例如:”张三 + 上海交大 + 视觉SLAM“。请按照格式备注,否则不予通过。添加成功后会根据研究方向邀请进入相关微信群。请勿在群内发送广告,否则会请出群,谢谢理解~