仅当不模糊时保存照片(拉普拉斯系数>200)?

2024-04-19 20:46:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我想保存/写不模糊的照片。如何将下面两个代码组合起来?在

import cv2

image = cv2.imread('./facesData/ID.jpg')
cv2.Laplacian(image, cv2.CV_64F).var()

while 1:
    ret, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.2, 8)
    for x,y,w,h in faces:

        sampleN = sampleN + 1
        cv2.imwrite("./facesData/ID." + str(sampleN) + ".jpg", gray[y:y+h, x:x+w])
        cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)
        cv2.waitKey(2)

    cv2.imshow('user', img)
    cv2.waitKey(1)

    if sampleN > 20:
        break

cap.release()
cv2.destroyAllWindows()

Tags: 代码imageimportidimgcv2照片jpg
2条回答

这会将模糊图像移到一个单独的文件夹(code source)。在

# import the necessary packages
import cv2
import os
from pathlib import Path

#%% Setup paths
script_dir = str(Path(__file__).parents[0]) # path this script is running in
source_images_dir = os.path.join(script_dir, 'images')

#%%
def variance_of_laplacian(image):
    # compute the Laplacian of the image and then return the focus
    # measure, which is simply the variance of the Laplacian
    return cv2.Laplacian(image, cv2.CV_64F).var()

#%% loop over the input images
threshold = 200

for file_name in os.listdir(source_images_dir):
    image_path = os.path.join(source_images_dir, file_name)
    image = cv2.imread(image_path) # load the image
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # convert to grayscale
    fm = variance_of_laplacian(image) # calculate blur
    text = "Not Blurry"

    # if the focus measure is less than the supplied threshold,
    # then the image should be considered "blurry"
    if fm >= threshold:
        text = "Blurry"

    #%% Once ready to move clear images, uncomment this section
    else:
        focused_images_path = os.path.join(script_dir,
                                           'blurry_images',
                                           file_name)
        os.rename(image_path, focused_images_path)

    #%% Comment out the following section when ready to batch move your images
    cv2.putText(image, "{}: {:.2f}".format(text, fm), (10, 30),
                cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 3)
    cv2.imshow("Image", image) # Press ENTER to cycle through images
    key = cv2.waitKey(0)

要使用它,请设置文件夹结构,如: enter image description here


最后,欢迎使用Stackoverflow:)来最大限度地提高您使用这个网站的价值(并帮助我们帮助您)尝试一下these tips

ret, frame = cap.read()
if face_extractor(frame) is not None:
    count = count+1;
    face = cv2.cvtColor(face, cv2.COLOR_BGR2GRAY)

    file_name_path = './facesData/ID.' +str(id)+ '.' +str(count)+ '.' + '.jpg'
    if cv2.Laplacian(face, cv2.CV_64F).var() >500:
        cv2.imwrite(file_name_path, face)

    else:
        count -= 1

     cv2.imshow('user', frame)

else:
    pass

if cv2.waitKey(1) == 13 or count == 20

相关问题 更多 >