使用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)