簡體   English   中英

如何在python中使用opencv讀取圖像的遮罩

[英]How to read the mask of an image using opencv in python

我正在kaggle中解決這個稱為Carvana Segmentation的挑戰。 數據集包含5088張圖像,每個圖像都有一個遮罩。 例如,以下是單個圖像(.jpg文件)及其對應的蒙版(.gif文件)。

在此處輸入圖片說明在此處輸入圖片說明

我能夠使用cv2讀取.jpg文件,但無法讀取.gif文件。 我用來讀取.gif文件的語法是

 >>> image = cv2.imread('filename.gif',cv2.IMREAD_GRAYSCALE)

當我嘗試打印圖像時,返回None

 >>> print(image) -> None

有人可以建議其他方法嗎

遵循此回購協議: https : //github.com/asharma327/Read_Gif_OpenCV_Python/blob/master/gif_to_pic.py

您可以執行以下操作來讀取圖像

import cv2
import os


def convert_gif_to_frames(gif):

    # Initialize the frame number and create empty frame list
    frame_num = 0
    frame_list = []

    # Loop until there are frames left
    while True:
        try:
            # Try to read a frame. Okay is a BOOL if there are frames or not
            okay, frame = gif.read()
            # Append to empty frame list
            frame_list.append(frame)
            # Break if there are no other frames to read
            if not okay:
                break
            # Increment value of the frame number by 1
            frame_num += 1
        except KeyboardInterrupt:  # press ^C to quit
            break

    return frame_list


def output_frames_as_pics(frame_list):

    # Reduce the list of frames by half to make the list more managable
    frame_list_reduce = frame_list[0::2]
    # Get the path of the current working directory
    path = os.getcwd()
    # Set then name of your folder
    '''Replace this name with what you want your folder name to be'''
    folder_name = 'Picturebook_Pics_Kiss'
    # If the folder does not exist, then make it
    if not os.path.exists(path + '/' + folder_name):
        os.makedirs(path + '/' + folder_name)

    for frames_idx in range(len(frame_list_reduce)):
        cv2.imwrite(os.path.join(path + '/' + folder_name, str(frames_idx+1) + '.png'), frame_list_reduce[frames_idx])

    return


gif = cv2.VideoCapture('/home/ahmedramzy/Documents/gif/giphy.gif')
# here you can get the frames and work on it
xx = convert_gif_to_frames(gif_kiss)
# here if you want to write it on hard disk using imwrite 
output_frames_as_pics(xx)

imageio允許讀取這樣的gif:

import imageio

img = imageio.imread('filename.gif')

您不能使用imread(),沒有針對該內置代碼的編解碼器(仍然是許可證問題)[ https://answers.opencv.org/question/185929/how-to-read-gif-in-python/]

由於您對python感興趣,因此可以使用此處提到的PIL庫。

from PIL import Image
im = Image.open("animation.gif")

# To iterate through the entire gif
try:
    while 1:
        im.seek(im.tell()+1)
        # do something to im
except EOFError:
    pass # end of sequence

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM