我有这几行代码,可以使用网络摄像头捕获图像,但图片的宽度和高度很大。这是我可以的方法吗 框架要小,以拍摄护照照片大小的图像。
我可以使用任何可用资源来实现这一目标。这就是我希望我的框架的样子,这样我就可以使用网络摄像头捕获从头到肩的图像。
附有示例图片
import cv2
key = cv2.waitKey(1)
webcam = cv2.VideoCapture(0)
while True:
try:
check, frame = webcam.read()
print(check) # prints true as long as the webcam is running
print(frame) # prints matrix values of each framecd
cv2.imshow("Capturing", frame)
key = cv2.waitKey(1)
if key == ord('s'):
cv2.imwrite(filename='saved_img.jpg', img=frame)
webcam.release()
img_new = cv2.imread('saved_img.jpg', cv2.IMREAD_UNCHANGED)
img_new = cv2.imshow("Captured Image", img_new) # SHOWS THE IMAGE AFTER CAPTURING
cv2.waitKey(1650)
cv2.destroyAllWindows()
print("captured images saved")
break
elif key == ord('q'):
print("Turning off camera.")
webcam.release()
print("Camera off.")
print("Program ended.")
cv2.destroyAllWindows()
break
except(KeyboardInterrupt):
print("Turning off camera.")
webcam.release()
print("Camera off.")
print("Program ended.")
cv2.destroyAllWindows()
break
以下是如何使用 Python/PIL 裁剪为 2in x 2in。我们需要使用 PIL 来设置密度。我不相信 OpenCV 允许这样做。我假设你想在中心裁剪。如果没有,例如从顶部,请告诉我。但是,除非您有一个允许指定裁剪位置的交互式系统,否则您无法考虑每张图片,即框架中的人有多大。
输入(假设固定 480x640 纵向模式尺寸):
import numpy as np
from PIL import Image
# read the input
img = Image.open('portrait.jpg')
# get dimensions (assume 480x640)
width, height = img.size
# for 2in x 2in printed result, we want to crop an aspect ratio of 1:1 in center
# so since the height will be larger than the width, we use the width for both dimensions
w2 = xcent = width//2
h2 = ycent = height//2
top = ycent - w2
left = xcent - w2
bottom = ycent + w2
right = xcent + w2
# crop input
crop = img.crop((left, top, right, bottom))
# get crop size
wd, ht = crop.size
# save image with density appropriate for 2in x 2in print
xprint = 2
yprint = 2
xdensity = wd//xprint
ydensity = ht//yprint
crop.save('portrait_2in_x_2in.jpg', dpi=(xdensity, ydensity))
# show cropped Image
crop.show()
裁剪结果: