python抠图

使用cv2实现蒙版扣取无背景图

复制代码
import cv2
import numpy as np
img = cv2.imread('I:/test/pythonProject/database/test4png.png') #文件地址,需全部地址,无汉字
cv2.imshow("img",img)   #显示原图像
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)      #转为灰度图
ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)  #转为二值图
contours, hierarchy = cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)#寻找轮廓
mask=np.zeros(img.shape,np.uint8)  #生成黑背景,即全为0
mask=cv2.drawContours(mask,contours,-1,(255,255,255),-1)  #绘制轮廓,形成掩膜
cv2.imshow("mask" ,mask)        #显示掩膜
result=cv2.bitwise_and(img,mask)   #按位与操作,得到掩膜区域
cv2.imshow("result" ,result)     #显示图像中提取掩膜区域
cv2.waitKey()
cv2.destroyAllWindows()
复制代码

 

 

 

 

 

 

识别人脸并框出

 

 

复制代码
import cv2
from imutils.object_detection import non_max_suppression
import numpy as np

img = cv2.imread("I:/test/pythonProject/database/test3.jpg")
orig = img.copy()

# 定义HOG对象,采用默认参数,或者按照下面的格式自己设置
defaultHog = cv2.HOGDescriptor()
# 设置SVM分类器,用默认分类器
defaultHog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())

# 这里对整张图片进行裁剪
# detect people in the image
(rects, weights) = defaultHog.detectMultiScale(img, winStride=(4, 4),padding=(8, 8), scale=1.05)
for (x, y, w, h) in rects:
    cv2.rectangle(orig, (x, y), (x + w, y + h), (0, 0, 255), 2)
rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects])
pick = non_max_suppression(rects, probs=None, overlapThresh=0.65)
for (xA, yA, xB, yB) in pick:
    cv2.rectangle(img, (xA, yA), (xB, yB), (0, 255, 0), 2)
cv2.imshow("Before NMS", orig)
cv2.imshow("After NMS", img)
#
# # 只对ROI进行裁剪,img[height_begin:height_end,width_begin:width_end]
# roi = img[0:200, 800:1600]
# cv2.imshow("roi", roi)
# cv2.imwrite("roi.jpg", roi)
# (rects, weights) = defaultHog.detectMultiScale(roi, winStride=(4, 4), padding=(8, 8), scale=1.05)
# rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects])
# pick = non_max_suppression(rects, probs=None, overlapThresh=0.65)
# for (xA, yA, xB, yB) in pick:
#     cv2.rectangle(roi, (xA, yA), (xB, yB), (0, 255, 0), 2)
#
# cv2.imshow("roi", roi)
# cv2.imwrite("roi_out.jpg", roi)
cv2.waitKey(0)
复制代码

 

posted @   韦德·沃兹  阅读(1186)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示