在python中从像素数据保存图像

2024-03-29 05:55:19 发布

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

我试图创建一个程序,将保存通过openCV canny边缘检测获得的像素数据的图像。现在,该程序将一个小图像文件保存在正确的路径中,但该图像文件不包含来自网络摄像头的任何数据

图像文件中应保存的内容示例: picture of edge detected room

与实际保存的内容相比:just a black rectangle

下面的代码:

import matplotlib.image as mpimg

import matplotlib.pyplot as plt

import numpy as np

from numpy import asarray

import PIL

from PIL import Image

import cv2


def LiveCamEdgeDetection_canny(image_color):
   
    threshold_1 = 100  #LINES

    threshold_2 = 50    #NOISE

    image_gray = cv2.cvtColor(image_color, cv2.COLOR_BGR2GRAY)

    canny = cv2.Canny(image_gray, threshold_1, threshold_2)

    return canny


# Main calling function to initialize webcam and apply edge detection

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()   
    cv2.imshow('Live Edge Detection', LiveCamEdgeDetection_canny(frame))
    #cv2.imshow('Webcam Video', frame)
    #print(LiveCamEdgeDetection_canny(frame))
    
    # Store pixel data
    pixels = [LiveCamEdgeDetection_canny(frame)]
    image_todraw = np.array(pixels)
    image_todraw = np.reshape(image_todraw, (720, 1280))
    image_todraw *= 255
    
    image_tosave = Image.fromarray(image_todraw.astype(np.uint8))
    image_tosave.save('/Users/user/Desktop/destinationFolder/RETRY.jpeg', 'JPEG')
    
    #print(image_tosave)

    if cv2.waitKey(1) == 'p': #13 Enter Key
        break
        
        
cap.release() # camera release 
cv2.destroyAllWindows()

我感谢你能给我的一切帮助


Tags: 数据imageimport程序thresholdas图像文件np