1

when i insert a grayscale image then the algorithm works if i insert a rgb image the output is wrong. is the way I work with the rgb image correct? I don't understand why can someone help me?

library used

from PIL import Image

import numpy as np from cv2 import cv2

 def lz77Compress (image,sw,lab):
    img = cv2.imread(image)
    print("Initial size", img)
    flat = np.array(img).flatten()
    #cv2.imshow("input", img)
    row = img.shape[0]
    col = img.shape[1]
    tot = row * col
    slidingWindows = sw
    lookAhead = lab 

array of tuyple and charactert

encodedTuple = np.array([]) 
encodedChar = np.array([])

pointer in the search buffer

sbPointer = 0
while sbSize + sbPointer < tot :
    max_match = 0
    max_match_go_back = 0        
    selChar = sbPointer + sbSize

empty sequence

   seqY = np.array([])
    for i in range(sbPointer,sbPointer + sbSize):
        if(flat[i] == encodeCharacters):
            seqY = np.append(seqY,i)

check if there is a match in the lookAheadBuffer

 if(seqY.size == 0 ):
        encodedTuple = np.append(encodedTuple,(0,0))
        encodedChar = np.append (encodedChar,encodeCharacters)
    else:

        for j in seqY:
        #lunghezza della corrispodenza
            matchLenght= 0
            returnBack = selChar -i
            it = 0 
            while selChar + it < tot :
                if flat[it + j] == flat[selChar + it]:
                    matchLenght +=1
                    it +=1
              # se non trova corrispondenze
                else: 
                    break
            if matchLenght>max_match:
               max_match = matchLenght
               returnBack = max_match_go_back

save corrispondence and tuple in array

encodedTuple = np.append(encodedTuple,(max_match_go_back,max_match))
encodedChar = np.append(encodedChar,flat[selChar + max_match - 1])
        
       sbPointer+= 1 +max_match

**save of encodedTuple, encodedChar , file compresses.txt and imsize of decompression **

print("Prova", encodedTuple, encodedChar)
print("ArrayBin",encodedTuple.tolist(), encodedChar.tolist())
np.save("encodedTuple", encodedTuple) 
np.save("encodedChar", encodedChar)
a = encodedTuple.tolist()
b = encodedChar.tolist()
c= (a,b)
print("File compresso in : Copressed.txt")
output = open("Compressed.txt","w+")
output.write(str(c))
imgSize = open('imgSize.txt', "w")
imgSize.write(str(row) + '\n')  # write row dimension
imgSize.write(str(col) + '\n')  # write col dimension
cv2.waitKey(0)
cv2.destroyAllWindows()

**Main **

path = "./im3.jpg"

lz77Compress (path,500,500)

giangri_93
  • 29
  • 3
  • RGB image has 3 channels (in most cases). Try adding `ch = img.shape[2]` after `col = img.shape[1]` and `tot = row * col * ch`. Or better: `tot = img.size`. In case it's not the problem, please post a code sample that reproduces the problem - a code that someone can copy, paste and execute. – Rotem Apr 02 '21 at 21:12
  • i added ch but now I have this probelm : File "c:/Users/anton/Desktop/Progetto/test.py", line 17, in lz77Compress (path,500,500) File "c:\Users\anton\Desktop\Progetto\image.py", line 35, in lz77Compress encodeCharacters = flat[selChar] IndexError: index 206 is out of bounds for axis 0 with size 206 – giangri_93 Apr 03 '21 at 07:28
  • I case you decide to post a code that I can actually execute, please let me know. – Rotem Apr 03 '21 at 08:06
  • @Rotem in the comment i can't poste the code because is long, i give you my link github github.com/Anto-9393/project-multimedia-lz77. Thanks for your Help – giangri_93 Apr 03 '21 at 12:38

1 Answers1

0

In most cases, RGB image has 3 color channels, and gray image has 1 color channel.

  • Assume img is a NumPy array that represents a gray image:
    img.shape is going to be (rows, cols), and img.size is rows*cols.
  • Assume img is a NumPy array that represents a RGB (or BGR) image:
    img.shape is going to be (rows, cols, ch), and img.size is rows*cols*ch.
    In case of RGB, ch = 3.

I downloaded your code from github.
I saw you already corrected the code to support RGB images.

I can't reproduce the error in line 35 of image.py
Did you fix it?

The issues I could find:

  • You are not closing the files:
    Close the files at the end of lz77Compress:

     # We must close the files.
     output.close()
     imgSize.close()
    

You better also close imsize after reading row, col, ch in lz77Decompressor.

  • When using cv2.imshow("output", decodeArray), you need the type of decodeArray to be uint8.
    You may use the following code to show the output:

     cv2.imshow("output", decodeArray.astype(np.uint8)) # Show as uint8
    

In case you want to support both gray and RGB, you can check if len(img.shape) is 2 or 3, and add some logic at the Decompressor.

Note:
I didn't review the entire code, so there might be problems that I missed.

Rotem
  • 30,366
  • 4
  • 32
  • 65
  • first of all I would like to thank you for your suggestions. I solved it but now I have a problem regarding the compression speed. With small images (205,204) the algorithm takes 1 minute instead with larger images the time increases a lot. How could I optimize the code? p.s are just starting out with python. – giangri_93 Apr 05 '21 at 10:29
  • When I need something to run fast, I use C and not Python. Loops in Python are very slow, so try to avoid long loops, when possible. Check your implementation to see if there are loops you can avoid. I don't know if it's relevant, but try to use vectorized operations (using NumPy) when adequate. If you can't avoid using loops, you may try [Cython](https://cython.org/) and/or [Numba](https://numba.pydata.org/). Please note that my Python experience is limited. – Rotem Apr 05 '21 at 11:35
  • https://github.com/Anto-9393/project-multimedia-lz77 I made some changes, the algorithm has speeded up but now the final image is only half visible. Any suggestions? – giangri_93 Apr 06 '21 at 17:34
  • Well... I know it's hard, but you will have to debug your code. – Rotem Apr 06 '21 at 19:24
  • @ Rotem : could you tell me why I have this problem in this algorithm? : https://stackoverflow.com/questions/67043929/valueerror-cannot-reshape-array-of-size-1-into-shape-500-700-3 – giangri_93 Apr 11 '21 at 10:36