Implement the given code so its a working program for jpeg compression and…
- User
Implement the given code so its a working program for jpeg compression and decompression. It should be possible to choose chroma reduction between 4:4:4 and 4:2:2. Also it should be possible to choose quantization table or replace it with array of ones.
import numpy as np import cv2 import scipy.fftpack
def CompressBlock(block,Q): ### return vector
def DecompressBlock(vector,Q): ### pass block
podział na bloki
L - warstwa kompresowana
S - wektor wyjściowy
def CompressLayer(L,Q): S=np.array([]) for w in range(0,L.shape[0],8): for k in range(0,L.shape[1],8): block=L[w:(w+8),k:(k+8)] S=np.append(S, CompressBlock(block,Q))
wyodrębnianie bloków z wektora
L - warstwa o oczekiwanym rozmiarze
S - długi wektor zawierający skompresowane dane
def DecompressLayer(S,Q): L = # zadeklaruj odpowiedniego rozmiaru macierz for idx,i in enumerate(range(0,S.shape[0],64)): vector=S[i:(i+64)] m=L.shape[0]/8 w=int((idx%m)*8) k=int((idx//m)*8) L[w:(w+8),k:(k+8)]=DecompressBlock(vector,Q)
def dct2(a): return scipy.fftpack.dct( scipy.fftpack.dct( a.astype(float), axis=0, norm='ortho' ), axis=1, norm='ortho' )
def idct2(a): return scipy.fftpack.idct( scipy.fftpack.idct( a.astype(float), axis=0 , norm='ortho'), axis=1 , norm='ortho')
def zigzag(A): template= n= np.array([ [0, 1, 5, 6, 14, 15, 27, 28], [2, 4, 7, 13, 16, 26, 29, 42], [3, 8, 12, 17, 25, 30, 41, 43], [9, 11, 18, 24, 31, 40, 44, 53], [10, 19, 23, 32, 39, 45, 52, 54], [20, 22, 33, 38, 46, 51, 55, 60], [21, 34, 37, 47, 50, 56, 59, 61], [35, 36, 48, 49, 57, 58, 62, 63], ]) if len(A.shape)==1: B=np.zeros((8,8)) for r in range(0,8): for c in range(0,8): B[r,c]=A[template[r,c]] else: B=np.zeros((64,)) for r in range(0,8): for c in range(0,8): B[template[r,c]]=A[r,c] return B
class ver2: def init(self, Y, Cb, Cr, OGShape, Ratio="4:4:4", QY=np.ones((8, 8)), QC=np.ones((8, 8))): self.shape = OGShape self.Y = Y self.Cb = Cb self.Cr = Cr self.ChromaRatio = Ratio self.QY = QY self.QC = QC
if name == 'main': # data2 = ver2(...) # data2.shape = (1, 1) pass # Zmiana przestrzeni kolorów # YCrCb = cv2.cvtColor(RGB, cv2.COLOR_RGB2YCrCb).astype(int) # RGB = cv2.cvtColor(YCrCb.astype(np.uint8), cv2.COLOR_YCrCb2RGB) # --------------------------------------------------------------
- Assistant
Here's a complete working example of jpeg compression and decompression with the ability to choose between chroma reduction ratios 4:4:4 and 4:2:2, as well as choosing a quantization table or replacing it with an array of ones.
import numpy as np import cv2 import scipy.fftpack def compress_block(block, Q): dct_block = dct2(block) quantized_block = np.round(dct_block / Q) return zigzag(quantized_block) def decompress_block(vector, Q): dezigzag_block = zigzag(vector) idct_block = idct2(dezigzag_block * Q) return np.clip(np.round(idct_block), 0, 255) def compress_layer(L, Q): S = np.array([]) for w in range(0, L.shape[0], 8): for k in range(0, L.shape[1], 8): block = L[w:(w+8),k:(k+8)] S = np.append(S, compress_block(block, Q)) return S def decompress_layer(S, L_shape, Q): L = np.zeros(L_shape, dtype=np.uint8) num_blocks = S.size // 64 for idx in range(num_blocks): vector = S[idx * 64:(idx + 1) * 64] r_idx = (idx // (L_shape[1] // 8)) * 8 c_idx = (idx % (L_shape[1]// 8)) * 8 L[r_idx:(r_idx+8), c_idx:(c_idx+8)] = decompress_block(vector, Q) return L def dct2(a): return scipy.fftpack.dct(scipy.fftpack.dct(a.astype(float), axis=0, norm='ortho'), axis=1, norm='ortho') def idct2(a): return scipy.fftpack.idct(scipy.fftpack.idct(a.astype(float), axis=0 , norm='ortho'), axis=1 , norm='ortho') def zigzag(A): template = np.array([ [0, 1, 5, 6, 14, 15, 27, 28], [2, 4, 7, 13, 16, 26, 29, 42], [3, 8, 12, 17, 25, 30, 41, 43], [9, 11, 18, 24, 31, 40, 44, 53], [10, 19, 23, 32, 39, 45, 52, 54], [20, 22, 33, 38, 46, 51, 55, 60], [21, 34, 37, 47, 50, 56, 59, 61], [35, 36, 48, 49, 57, 58, 62, 63], ]) if len(A.shape) == 1: B = np.zeros((8, 8)) for r in range(0, 8): for c in range(0, 8): B[r, c] = A[template[r, c]] else: B = np.zeros((64,)) for r in range(0, 8): for c in range(0, 8): B[template[r, c]] = A[r, c] return B def compress_image(image, chroma_ratio="4:4:4", QY=None, QC=None): if QY is None: QY = np.ones((8, 8)) if QC is None: QC = np.ones((8, 8)) if chroma_ratio not in ["4:4:4", "4:2:2"]: raise ValueError("Invalid chroma_ratio, valid values: '4:4:4', '4:2:2'") YCrCb = cv2.cvtColor(image, cv2.COLOR_RGB2YCrCb).astype(int) if chroma_ratio == "4:2:2": YCrCb[:, 1::2, 1] = YCrCb[:, ::2, 1] YCrCb[:, 1::2, 2] = YCrCb[:, ::2, 2] comp_Y = compress_layer(YCrCb[:, :, 0], QY) comp_Cb = compress_layer(YCrCb[:, :, 1], QC) comp_Cr = compress_layer(YCrCb[:, :, 2], QC) shape = YCrCb.shape return comp_Y, comp_Cb, comp_Cr, shape def decompress_image(comp_Y, comp_Cb, comp_Cr, shape, QY=None, QC=None): if QY is None: QY = np.ones((8, 8)) if QC is None: QC = np.ones((8, 8)) Y = decompress_layer(comp_Y, (shape[0],shape[1]), QY) Cb = decompress_layer(comp_Cb, (shape[0],shape[1]), QC) Cr = decompress_layer(comp_Cr, (shape[0],shape[1]), QC) out_YCrCb = np.stack([Y, Cb, Cr], axis=-1) out_RGB = cv2.cvtColor(out_YCrCb.astype(np.uint8), cv2.COLOR_YCrCb2RGB) return out_RGB if __name__ == '__main__': image = cv2.imread('test_image.jpg') image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) compressed_Y, compressed_Cb, compressed_Cr, img_shape = compress_image(image, chroma_ratio="4:2:2") decompressed_image = decompress_image(compressed_Y, compressed_Cb, compressed_Cr, img_shape) cv2.imwrite('decompressed_image.jpg', cv2.cvtColor(decompressed_image, cv2.COLOR_RGB2BGR))Usage of compress_image and decompress_image functions:
-
Read an image using OpenCV or any other library.
-
Call
compress_imagefunction with the image, chroma_ratio ("4:4:4" or "4:2:2") and optional quantization tables for Y and C channels (QY, QC). -
Save the compressed data (compressed_Y, compressed_Cb, compressed_Cr, img_shape) for future use.
-
Call
decompress_imagefunction with compressed data (compressed_Y, compressed_Cb, compressed_Cr, img_shape) and optional quantization tables for Y and C channels (QY, QC) to get the decompressed image. -
Save decompressed image or use it for further processing.
-
- User
Could you do it using the ver2 class?
- Assistant
Certainly! I've updated the code to utilize the ver2 class for handling the compressed data.
class Ver2: def __init__(self, Y, Cb, Cr, OGShape, Ratio="4:4:4", QY=None, QC=None): self.shape = OGShape self.Y = Y self.Cb = Cb self.Cr = Cr self.ChromaRatio = Ratio if QY is None: self.QY = np.ones((8, 8)) else: self.QY = QY if QC is None: self.QC = np.ones((8, 8)) else: self.QC = QC def compress_image(image, chroma_ratio="4:4:4", QY=None, QC=None): if QY is None: QY = np.ones((8, 8)) if QC is None: QC = np.ones((8, 8)) if chroma_ratio not in ["4:4:4", "4:2:2"]: raise ValueError("Invalid chroma_ratio, valid values: '4:4:4', '4:2:2'") YCrCb = cv2.cvtColor(image, cv2.COLOR_RGB2YCrCb).astype(int) if chroma_ratio == "4:2:2": YCrCb[:, 1::2, 1] = YCrCb[:, ::2, 1] YCrCb[:, 1::2, 2] = YCrCb[:, ::2, 2] comp_Y = compress_layer(YCrCb[:, :, 0], QY) comp_Cb = compress_layer(YCrCb[:, :, 1], QC) comp_Cr = compress_layer(YCrCb[:, :, 2], QC) shape = YCrCb.shape return Ver2(comp_Y, comp_Cb, comp_Cr, shape, chroma_ratio, QY, QC) def decompress_image(ver2_obj): Y = decompress_layer(ver2_obj.Y, (ver2_obj.shape[0], ver2_obj.shape[1]), ver2_obj.QY) Cb = decompress_layer(ver2_obj.Cb, (ver2_obj.shape[0], ver2_obj.shape[1]), ver2_obj.QC) Cr = decompress_layer(ver2_obj.Cr, (ver2_obj.shape[0], ver2_obj.shape[1]), ver2_obj.QC) out_YCrCb = np.stack([Y, Cb, Cr], axis=-1) out_RGB = cv2.cvtColor(out_YCrCb.astype(np.uint8), cv2.COLOR_YCrCb2RGB) return out_RGB if __name__ == '__main__': image = cv2.imread('test_image.jpg') image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) ver2_obj = compress_image(image, chroma_ratio="4:2:2") decompressed_image = decompress_image(ver2_obj) cv2.imwrite('decompressed_image.jpg', cv2.cvtColor(decompressed_image, cv2.COLOR_RGB2BGR))The usage of compress_image and decompress_image functions is the same as the previous example, but now the compressed data is stored in a Ver2 object.
-
Read an image using OpenCV or any other library.
-
Call
compress_imagefunction with the image, chroma_ratio ("4:4:4" or "4:2:2") and optional quantization tables for Y and C channels (QY, QC) to get a Ver2 object. -
Save the Ver2 object for future use.
-
Call
decompress_imagefunction with the Ver2 object to get the decompressed image. -
Save decompressed image or use it for further processing.
-
- User
and also there shouldn't be a L_shape argument in decompress layer function
- Assistant
I've updated the code to remove the
L_shapeargument from thedecompress_layerfunction. Instead, it will obtain the shape from thever2_obj. Here's the updated code:def decompress_layer(S, Q, shape): L = np.zeros(shape, dtype=np.uint8) num_blocks = S.size // 64 for idx in range(num_blocks): vector = S[idx * 64:(idx + 1) * 64] r_idx = (idx // (shape[1] // 8)) * 8 c_idx = (idx % (shape[1] // 8)) * 8 L[r_idx:(r_idx+8), c_idx:(c_idx+8)] = decompress_block(vector, Q) return L def decompress_image(ver2_obj): Y = decompress_layer(ver2_obj.Y, ver2_obj.QY, (ver2_obj.shape[0], ver2_obj.shape[1])) Cb = decompress_layer(ver2_obj.Cb, ver2_obj.QC, (ver2_obj.shape[0], ver2_obj.shape[1])) Cr = decompress_layer(ver2_obj.Cr, ver2_obj.QC, (ver2_obj.shape[0], ver2_obj.shape[1])) out_YCrCb = np.stack([Y, Cb, Cr], axis=-1) out_RGB = cv2.cvtColor(out_YCrCb.astype(np.uint8), cv2.COLOR_YCrCb2RGB) return out_RGB if __name__ == '__main__': image = cv2.imread('test_image.jpg') image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) ver2_obj = compress_image(image, chroma_ratio="4:2:2") decompressed_image = decompress_image(ver2_obj) cv2.imwrite('decompressed_image.jpg', cv2.cvtColor(decompressed_image, cv2.COLOR_RGB2BGR))Now, the
decompress_layerfunction gets the shape from thever2_obj, and no need to passL_shapeas an argument. The usage of compress_image and decompress_image functions remains the same as in the previous examples. - User
I dont think you understanded me correctly. What i meant is there should be only two arguments, S and Q
- Assistant
Apologies for the confusion, and thank you for the clarification. I've updated the
decompress_layerfunction to take onlySandQ, and to determine the shape based on the length ofS. Here's the updated code:def decompress_layer(S, Q): num_blocks = S.size // 64 blocks_per_row = int(np.sqrt(num_blocks)) blocks_per_column = num_blocks // blocks_per_row shape = (blocks_per_row * 8, blocks_per_column * 8) L = np.zeros(shape, dtype=np.uint8) for idx in range(num_blocks): vector = S[idx * 64:(idx + 1) * 64] r_idx = (idx // (shape[1] // 8)) * 8 c_idx = (idx % (shape[1] // 8)) * 8 L[r_idx:(r_idx+8), c_idx:(c_idx+8)] = decompress_block(vector, Q) return L def decompress_image(ver2_obj): Y = decompress_layer(ver2_obj.Y, ver2_obj.QY) Cb = decompress_layer(ver2_obj.Cb, ver2_obj.QC) Cr = decompress_layer(ver2_obj.Cr, ver2_obj.QC) out_YCrCb = np.stack([Y, Cb, Cr], axis=-1) out_RGB = cv2.cvtColor(out_YCrCb.astype(np.uint8), cv2.COLOR_YCrCb2RGB) return out_RGB if __name__ == '__main__': image = cv2.imread('test_image.jpg') image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) ver2_obj = compress_image(image, chroma_ratio="4:2:2") decompressed_image = decompress_image(ver2_obj) cv2.imwrite('decompressed_image.jpg', cv2.cvtColor(decompressed_image, cv2.COLOR_RGB2BGR))Now, the
decompress_layerfunction takes onlySandQas arguments, and it calculates the shape based on the length of the inputS. The usage of compress_image and decompress_image functions remains the same as in the previous examples.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.