def __init__(self, filename, mode):
     self.filename = filename
     self.mode = mode
     self.width = 720
     self.height = 1280
     self.frame_len = 0
     self.bStream = Stream()
     self.gol = Golomb(4)
     self.totalTime = 0
Exemple #2
0
    def EncodeInteruptedValue(self):
        self.IndexComuptation()
        self.Errval = self.PredictionErrorRunInteruption()
        self.Errval = self.ErrorCumpotationForRunInterruption(self.Errval)

        #
        TEMP = 0
        if (self.RItype == 0):
            TEMP = self.A[365]
        else:
            TEMP = self.A[366] + (self.N[366] >> 1)

        self.contextOfX = self.RItype + 365
        k = 0
        while ((self.N[self.contextOfX] << k) < TEMP):
            k += 1

        #
        mmap = 0
        if ((k == 0) and (self.Errval > 0)
                and (2 * self.Nn[self.contextOfX] < self.N[self.contextOfX])):
            mmap = 1
        elif ((self.Errval < 0)
              and (2 * self.Nn[self.contextOfX] >= self.N[self.contextOfX])):
            mmap = 1
        elif ((self.Errval < 0) and (k != 0)):
            mmap = 1
        else:
            mmap = 0

        #
        EMErrval = int(2 * abs(self.Errval) - self.RItype - mmap)

        if (not self.SIGNinterupt):
            return
        #print(self.byteManager, k, EMErrval, self.LIMIT - self.J[self.PrevRunIndex] - 1, self.qbpp)
        GB = Golomb()
        self.byteManager = GB.Encode(
            self.byteManager, k, EMErrval,
            self.LIMIT - self.J[self.PrevRunIndex] - 1, self.qbpp)

        #
        if (self.Errval < 0):
            self.Nn[self.contextOfX] += 1

        self.A[self.contextOfX] += ((EMErrval + 1 - self.RItype) >> 1)

        if (self.N[self.contextOfX] == self.RESET):
            self.A[self.contextOfX] = self.A[self.contextOfX] >> 1
            self.N[self.contextOfX] = self.N[self.contextOfX] >> 1
            self.Nn[self.contextOfX] = self.Nn[self.contextOfX] >> 1

        self.N[self.contextOfX] = self.N[self.contextOfX] + 1
Exemple #3
0
    def RegularModeProcessing(self):
        self.Quantize()
        self.PredictionPx()
        self.PredictionCorrect()
        errval = self.CalculateErrorValue()
        errval = self.ComputeRx(errval)
        errval = self.ReductionOfError(errval)

        k = 0
        while ((self.N[self.contextOfX] << k) < self.A[self.contextOfX]):
            k += 1

        MError = int(self.ErrorMapping(errval, k))
        GB = Golomb()
        self.byteManager = GB.Encode(self.byteManager, k, MError, self.LIMIT,
                                     self.qbpp)
        self.UpdateVariables(errval)
        self.UpdateBiasVariable()
    def __init__(self, file_path):
        self.file_path = file_path

        # Get our header info
        with open(self.file_path, "rb") as frame_reader:
            self.header = (frame_reader.readline()).decode("UTF-8")

        header_info = self.header.split(" ")
        self.frame_type = "420"
        print(self.header)

        for info in header_info:
            info = info.rstrip()
            if info[0] == "W":
                self.width = int(info.replace("W", ""))
            elif info[0] == "H":
                self.height = int(info.replace("H", ""))
            elif info[0] == "F":
                self.fps = info.replace("F", "")
            elif info[0] == "C":
                info = info.replace("C", "")
                if info.startswith("420"):
                    self.frame_type = "420"
                if info.startswith("422"):
                    self.frame_type = "422"
                if info.startswith("444"):
                    self.frame_type = "444"
            elif info[0] == "G":
                self.gomby = Golomb(int(info[1:]))
            elif info[0] == "M":
                self.decompress_mode = info[1:]

        if self.frame_type == "420":
            self.frame = Frame420(self.height, self.width)
        if self.frame_type == "422":
            self.frame = Frame422(self.height, self.width)
        if self.frame_type == "444":
            self.frame = Frame444(self.height, self.width)
import time
import math
import os
bitstream = BitStream(sys.argv[1], 'rb', read_FirstLine=True)
print(bitstream.first_line)
params = str(bitstream.first_line)[2:-3].split(" ")

width = int(params[0])

height = int(params[1])

formato = params[2]

m = int(params[3])

golomb = Golomb(m, bitstream)
bt2 = BitStream(
    sys.argv[2], 'wb',
    "YUV4MPEG2 W" + str(width) + " H" + str(height) + " F50:1 Ip A1:1\n")
#write_file = open(sys.argv[2], 'wb')
#write_file.write(("YUV4MPEG2 W"+str(width)+" H"+str(height)+" F50:1 Ip A1:1\n").encode("utf-8"))

r_size = math.ceil(math.log2(m))

if formato == '444':
    uv_shape = (height, width)
elif formato == '422':
    uv_shape = (height, (width // 2))
elif formato == '420':
    uv_shape = (height // 2, width // 2)
class VideoCodec:
    def __init__(self, file_path):
        self.file_path = file_path

        # Get our header info
        with open(self.file_path, "rb") as frame_reader:
            self.header = (frame_reader.readline()).decode("UTF-8")

        header_info = self.header.split(" ")
        self.frame_type = "420"
        print(self.header)

        for info in header_info:
            info = info.rstrip()
            if info[0] == "W":
                self.width = int(info.replace("W", ""))
            elif info[0] == "H":
                self.height = int(info.replace("H", ""))
            elif info[0] == "F":
                self.fps = info.replace("F", "")
            elif info[0] == "C":
                info = info.replace("C", "")
                if info.startswith("420"):
                    self.frame_type = "420"
                if info.startswith("422"):
                    self.frame_type = "422"
                if info.startswith("444"):
                    self.frame_type = "444"
            elif info[0] == "G":
                self.gomby = Golomb(int(info[1:]))
            elif info[0] == "M":
                self.decompress_mode = info[1:]

        if self.frame_type == "420":
            self.frame = Frame420(self.height, self.width)
        if self.frame_type == "422":
            self.frame = Frame422(self.height, self.width)
        if self.frame_type == "444":
            self.frame = Frame444(self.height, self.width)

    def play_video(self):
        with open(self.file_path, "rb") as stream:

            line = stream.readline()
            while True:
                try:
                    line = stream.readline()
                    self.frame.set_frame(stream)
                    BGR = self.frame.show_frame()

                    # Display the image with OpenCV
                    cv2.imshow('image', BGR)
                    if cv2.waitKey(25) & 0xFF == ord('q'):
                        break

                except ValueError:
                    print("Finished showing video")
                    break

            cv2.destroyAllWindows()

    def decompress_video(self, decompress_path):
        with open(decompress_path, "wb") as write_stream:
            #Get the bitstream to read the compression
            read_stream = BitStream(self.file_path)
            read_stream.set_offset(len(self.header) * 8)

            #Write the header for the video
            write_stream.write(self.header.encode())
            write_stream.write("FRAME\n".encode())

            #This marks the start of decompression
            number_of_numbers = 0
            array_of_nums = []

            counter = 0
            counter_bits = 0
            while read_stream.read_bits(5000):
                got_number = self.gomby.add_bits(read_stream.get_bit_array())

                read_stream.delete_bits(5000)
                counter_bits += 1

                if got_number:
                    nums = self.gomby.decode_nums()
                    number_of_numbers += len(nums)
                    array_of_nums += nums
                    print("Decompressed", number_of_numbers)
                    print("Need to get", self.frame.limit_to_convert)

                if number_of_numbers >= self.frame.limit_to_convert:
                    counter += 1
                    print("Decompressing frame: ", counter)

                    array_of_nums = self.frame.set_frame_by_array(
                        array_of_nums)
                    y, u, v = self.frame.decompress_frame(self.decompress_mode)

                    write_stream.write(y.astype(np.uint8))
                    write_stream.write(u.astype(np.uint8))
                    write_stream.write(v.astype(np.uint8))
                    write_stream.write("FRAME\n".encode())
                    number_of_numbers -= self.frame.limit_to_convert
                    print("Finished writing decompressed frame, now only have",
                          number_of_numbers)

            num_bits = read_stream.read_allbits()
            got_number = self.gomby.add_bits(read_stream.get_bit_array())
            if got_number:
                nums = self.gomby.decode_nums()
                array_of_nums += nums

                ## At this point we have all of the frame saved in memory, we will now start to divide it in frames to proceed to decompressing
                array_of_nums = self.frame.set_frame_by_array(array_of_nums)

                y, u, v = self.frame.decompress_frame(self.decompress_mode)

                write_stream.write(y.astype(np.uint8))
                write_stream.write(u.astype(np.uint8))
                write_stream.write(v.astype(np.uint8))
                print("Finished writing decompressed frame")
                #girar
            print("Finished writing decompressed frame")

    def compress_video(self, compress_path, mode="JPEG-1"):
        if mode not in ["JPEG-" + str(i)
                        for i in range(1, 8)] and mode != "JPEG-LS":
            print("Invalid mode")
            return None
        with open(self.file_path, "rb") as stream:
            line = stream.readline()

            gomby = Golomb(4)
            bit_stream = BitStream()

            header = self.header[:-1] + " G" + str(
                gomby.encoding_parameter) + " M" + mode + "\n"

            with open(compress_path, "wb") as file_path:
                file_path.write(header.encode())

            counter = 0

            while True:
                start_time = time()
                if counter > 2:
                    break
                counter += 1
                print("Compressing frame: ", counter)
                try:
                    line = stream.readline()
                except ValueError:
                    print("Finished compressing")
                    break
                line = stream.readline()
                self.frame.set_frame(stream)
                start = time()
                compressed_frame = self.frame.compress_frame(mode)
                print("Compressed in ", time() - start)
                y = compressed_frame[0]
                u = compressed_frame[1]
                v = compressed_frame[2]

                for x in np.nditer(y):
                    bit_stream.add_to_bit_array(gomby.encode(int(x)))

                #bit_stream.write_allbits(compress_path)

                print("Finished compressing Y")

                for x in np.nditer(u):
                    bit_stream.add_to_bit_array(gomby.encode(int(x)))

                #bit_stream.write_allbits(compress_path)

                print("Finished compressing U")

                for x in np.nditer(v):
                    bit_stream.add_to_bit_array(gomby.encode(int(x)))

                bit_stream.write_allbits(compress_path)

                print("Finished compressing in", time() - start_time)

            bit_stream.close(compress_path)
    def compress_video(self, compress_path, mode="JPEG-1"):
        if mode not in ["JPEG-" + str(i)
                        for i in range(1, 8)] and mode != "JPEG-LS":
            print("Invalid mode")
            return None
        with open(self.file_path, "rb") as stream:
            line = stream.readline()

            gomby = Golomb(4)
            bit_stream = BitStream()

            header = self.header[:-1] + " G" + str(
                gomby.encoding_parameter) + " M" + mode + "\n"

            with open(compress_path, "wb") as file_path:
                file_path.write(header.encode())

            counter = 0

            while True:
                start_time = time()
                if counter > 2:
                    break
                counter += 1
                print("Compressing frame: ", counter)
                try:
                    line = stream.readline()
                except ValueError:
                    print("Finished compressing")
                    break
                line = stream.readline()
                self.frame.set_frame(stream)
                start = time()
                compressed_frame = self.frame.compress_frame(mode)
                print("Compressed in ", time() - start)
                y = compressed_frame[0]
                u = compressed_frame[1]
                v = compressed_frame[2]

                for x in np.nditer(y):
                    bit_stream.add_to_bit_array(gomby.encode(int(x)))

                #bit_stream.write_allbits(compress_path)

                print("Finished compressing Y")

                for x in np.nditer(u):
                    bit_stream.add_to_bit_array(gomby.encode(int(x)))

                #bit_stream.write_allbits(compress_path)

                print("Finished compressing U")

                for x in np.nditer(v):
                    bit_stream.add_to_bit_array(gomby.encode(int(x)))

                bit_stream.write_allbits(compress_path)

                print("Finished compressing in", time() - start_time)

            bit_stream.close(compress_path)
class TimeEncoder:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
        self.width = 720
        self.height = 1280
        self.frame_len = 0
        self.bStream = Stream()
        self.gol = Golomb(4)
        self.totalTime = 0

    def encode(self):
        f = open(self.filename, "rb")
        frame = f.readline().decode('utf-8')
        rgb = np.zeros((self.height, self.width, 3), dtype=np.uint8)
        blockMatrix = [[[Block(8, 8) for a in range(0, 160)]
                        for b in range(0, 90)] for c in range(0, 3)]
        finalMatrix = np.zeros((self.width, self.height))
        if self.mode == '4:4:4':
            #for r in range(0, 2):
            self.frame_len = self.width * self.height * 3
            x = f.readline()
            raw = f.read(self.frame_len)
            y = np.frombuffer(raw,
                              dtype=np.uint8,
                              count=self.width * self.height)
            u = np.frombuffer(raw,
                              dtype=np.uint8,
                              count=self.width * self.height,
                              offset=self.width * self.height)
            v = np.frombuffer(raw,
                              dtype=np.uint8,
                              count=self.width * self.height,
                              offset=self.width * self.height * 2)
            y = y.reshape(self.width, self.height)
            u = u.reshape(self.width, self.height)
            v = v.reshape(self.width, self.height)
            currentFrame = [[[Block(8, 8) for a in range(0, 160)]
                             for b in range(0, 90)] for c in range(0, 3)]
            compensatedMatrix = [[[Block(8, 8) for a in range(0, 160)]
                                  for b in range(0, 90)] for c in range(0, 3)]
            finalBlockMatrix = [[[Block(8, 8) for a in range(0, 160)]
                                 for b in range(0, 90)] for c in range(0, 3)]
            for i in range(0, 90):
                for j in range(0, 160):
                    for l in range(0, 8):
                        for m in range(0, 8):
                            currentFrame[0][i][j].setData(
                                l, m, y[l + i * 8][m + j * 8])
                            currentFrame[1][i][j].setData(
                                l, m, u[l + i * 8][m + j * 8])
                            currentFrame[2][i][j].setData(
                                l, m, v[l + i * 8][m + j * 8])
            for z in range(0, 3):
                if z == 0:
                    self.bStream.setMatrix('y')
                    #cMatrix = y
                    #bMatrix = currentY
                elif z == 1:
                    self.bStream.setMatrix('u')
                    #cMatrix = u
                    #bMatrix = currentU
                else:
                    self.bStream.setMatrix('v')
                    #cMatrix = v
                    #bMatrix = currentV
                for i in range(0, 90):
                    for j in range(0, 160):
                        refBlock = blockMatrix[z][i][j]
                        currentBlock = currentFrame[z][i][j]
                        #currentBlock.showAll()
                        val = refBlock.compareBlock(currentBlock)
                        if val != 1:
                            compensatedMatrix[z][i][
                                j] = refBlock.searchSimilar(
                                    currentFrame, 1, z, i, j)
                            currentFrame[z][i][j] = currentBlock
                        #currentBlock.showAll()
                        #compensatedMatrix[z][i][j].showAll()
                        finalBlockMatrix[z][i][j] = compensatedMatrix[z][i][
                            j].subtractBlock(currentBlock)
                for i in range(0, 90):
                    for j in range(0, 160):
                        for m in range(0, 8):
                            for n in range(0, 8):  #ERRO AQUI FAZER CONTAS
                                finalMatrix[m + i * 8][
                                    n +
                                    j * 8] = finalBlockMatrix[z][i][j].getData(
                                        m, n)
                self.writeData(finalMatrix, '1')
            self.bStream.writeAll('timeOut.txt')
            self.bStream.resetAll()

    def writeData(self, matrix, predictorType):
        for i in range(0, self.width):
            for j in range(0, self.height):
                x = int(matrix[i][j])
                p = int(self.predictor(matrix, i, j, predictorType))
                e = x - p
                if e < 0:
                    e = 2 * abs(e) - 1
                else:
                    e = 2 * e
                enc = self.gol.encode(e)
                nu = ''.join(str(e) for e in enc)
                self.bStream.writeBits(int(nu, 2), len(enc))

    def encodeTest(self):
        f = open(self.filename, "rb")
        frame = f.readline().decode('utf-8')
        rgb = np.zeros((self.height, self.width, 3), dtype=np.uint8)
        blockMatrix = [[[Block(8, 8) for a in range(0, 160)]
                        for b in range(0, 90)] for c in range(0, 3)]
        if self.mode == '4:4:4':
            #for r in range(0, 2):
            self.frame_len = self.width * self.height * 3
            x = f.readline()
            raw = f.read(self.frame_len)
            y = np.frombuffer(raw,
                              dtype=np.uint8,
                              count=self.width * self.height)
            u = np.frombuffer(raw,
                              dtype=np.uint8,
                              count=self.width * self.height,
                              offset=self.width * self.height)
            v = np.frombuffer(raw,
                              dtype=np.uint8,
                              count=self.width * self.height,
                              offset=self.width * self.height * 2)
            y = y.reshape(self.width, self.height)
            u = u.reshape(self.width, self.height)
            v = v.reshape(self.width, self.height)
            for z in range(0, 3):
                if z == 0:
                    self.bStream.setMatrix('y')
                    cMatrix = y
                elif z == 1:
                    self.bStream.setMatrix('u')
                    cMatrix = u
                else:
                    self.bStream.setMatrix('v')
                    cMatrix = v
                for i in range(0, 90):
                    for j in range(0, 160):
                        refBlock = blockMatrix[z][i][j]
                        flag = True
                        for l in range(0, 8):
                            for m in range(0, 8):
                                w = int(l + i * 8)
                                h = int(m + j * 8)
                                if refBlock.getData(
                                        l, m) != cMatrix[w][h] and flag:
                                    flag = False
                                    l = 0
                                    m = 0
                                if not flag:
                                    block = Block(8, 8)
                                    x = int(cMatrix[w][h])
                                    p = int(self.predictor(cMatrix, w, h, '1'))
                                    e = x - p
                                    if e < 0:
                                        e = 2 * abs(e) - 1
                                    else:
                                        e = 2 * e
                                    enc = self.gol.encode(e)
                                    nu = ''.join(str(e) for e in enc)
                                    self.bStream.writeBits(
                                        int(nu, 2), len(enc))
                                    block.setData(l, m, x)
                        if not flag:
                            blockMatrix[0][i][j] = block
            self.bStream.writeAll('timeOut.txt')
            self.bStream.resetAll()

    def decode(self):
        pass

    def predictor(self, matrix, i, j, tipo):
        a = 0
        b = 0
        c = 0
        if tipo == '1':
            if j > 0:
                return matrix[i][j - 1]
            return 0
        elif tipo == '2':
            if i > 0:
                return matrix[i - 1][j]
            return 0
        elif tipo == '3':
            if i > 0 and j > 0:
                return matrix[i - 1][j - 1]
            return 0
        else:
            if j > 0:
                a = matrix[i][j - 1]
                if i > 0:
                    b = matrix[i - 1][j]
                    c = matrix[i - 1][j - 1]
            elif i > 0:
                b = matrix[i - 1][j]
            if tipo == '4':
                return a + b - c
            elif tipo == '5':
                return a + (b - c) / 2
            elif tipo == '6':
                return b + (a - c) / 2
            elif tipo == '7':
                return (a + b) / 2
            elif tipo == 'jpegLS':
                if c >= max(a, b):
                    return min(a, b)
                elif c <= min(a, b):
                    return max(a, b)
                else:
                    return int(a) + int(b) - int(c)
import cv2
import numpy as np
from Frame import Frame
from Video import Video
from Bitstream import BitStream
from Golomb import Golomb
import sys
import time

video = Video(sys.argv[1])
m = 5
params = "" + str(video.width) + " " + str(video.height) + " " + str(
    video.formato) + " " + str(m) + "\n"

bitstream = BitStream(sys.argv[2], 'wb', params)
golomb = Golomb(m, bitstream)

fnum = 0
while True:
    t = time.time()
    frame_read = video.getFrame()

    if frame_read is None:
        break

    frame = Frame(frame_read)

    encodedFrame = frame.preditiveEncodingJPEG_LS()
    fnum += 1
    print(fnum)
from Golomb import Golomb
from Bitstream import BitStream
import sys

bt = BitStream("text1.txt", "wb", init_message="Ola\n")
g = Golomb(5, bt)

encoded2 = g.encode2(int(sys.argv[1]))
bt.endWrite()

bt2 = BitStream("text1.txt", "rb", read_FirstLine=True)
g2 = Golomb(5, bt2)
decoded2 = g2.decode()
print(bt2.first_line)
print(decoded2)