影象 – 如何使用Alpha通道讀取動畫GIF
在MATLAB中使用.gif動畫進行一些測試時,我意識到我無法讀取gif的透明度.
例:
ofollow,noindex" target="_blank">(Original source of the gif)
如果我做
[img,cmap]=imread('Finnandjake.gif');
img是4D,具有冗餘的第三維(奇怪).擠壓它(img = squeeze(img);),如果我顯示它(imshow(img(:,:,30),cmap)):
透明度消失,使用影象中的另一種顏色作為背景,從而刪除功能.然而
[img,cmap,alpha]=imread('Finnandjake.gif');
返回一個空的alpha.顯然,Alpha的資訊在影象的某處,我如何在MATLAB中讀取它?
提供了程式碼.已釋出的版本與OCTAVE相容,並附帶一些文件.
我想出了這個解決方案.返回引數是堆疊影象,色彩對映和索引對應於透明度.
%do not use, instead use: http://www.mathworks.com/matlabcentral/fileexchange/55693-transparentgifread-filename- function [stack,map,transparent]=transparentGifRead(filename) if ~exist(filename,'file') error('file %s does not exist',filename); end info=imfinfo(filename); %Check if color map for all frames is the same if any(any(any(diff(cat(3,info.ColorTable),[],3)))) error('inconsistent color map') else map=info(1).ColorTable; end %Check if transparent color for all frames is the same if any(diff([info.TransparentColor])) error('inconsistent transparency information') else transparent=info(1).TransparentColor-1; end import java.io.* str = javax.imageio.ImageIO.createImageInputStream(java.io.File(filename)); t = javax.imageio.ImageIO.getImageReaders(str); reader = t.next(); reader.setInput(str); numframes = reader.getNumImages(true); for imageix = 1:numframes data = reader.read(imageix-1).getData(); height = data.getHeight(); width = data.getWidth(); data2 = reader.read(imageix-1).getData().getPixels(0,0,width,height,[]); if imageix == 1 stack=zeros(height,width,1,numframes,'uint8'); end %row major vs column major fix stack(:,:,1,imageix) = reshape(data2,[width height]).';%' end str.close(); end
一些演示程式碼將彩色透明畫素綠色:
[stack,map,transparent]=transparentGifRead('tr.gif'); map(transparent+1,:)=[0,1,0] %offset 1 because uint8 starts at 0 but indices at 1 for frame=1:size(stack,ndims(stack)) imshow(stack(:,:,frame),map); pause(1/25); end
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/34970064/how-to-read-an-animated-gif-with-alpha-channel