Blame view

mjpeg/__init__.py 14.2 KB
2b474806   Chunk   init.
1
2
## -*- coding: utf-8 -*-

c6c61f81   Chunk   staged.
3
from libmjsteg import Jsteg
2b474806   Chunk   init.
4

f4b5291c   Chunk   Qaulity Calculati...
5
__all__ = ['Jpeg', 'colorMap', 'diffblock', 'diffblocks']
2b474806   Chunk   init.
6
7
8
9
10
11
12
13
14

# We need standard components from :mod:`numpy`, and some auxiliary
# functions from submodules.
#
# ::

import numpy.random as rnd
from numpy import shape
import numpy as np
548d95dc   Chunk   steganography(F3 ...
15
import pylab as plt
2b474806   Chunk   init.
16
17
18

import base
from dct import bdct, ibdct
f4b5291c   Chunk   Qaulity Calculati...
19
from compress import *
2b474806   Chunk   init.
20
21
22
23
24
25
26
27
28
29
30
31

# The colour codes are defined in the JPEG standard.  We store
# them here for easy reference by name::

colorCode = {
    "GRAYSCALE": 1,
    "RGB": 2,
    "YCbCr": 3,
    "CMYK": 4,
    "YCCK": 5
}

6cbb3879   Chunk   F4 updated.
32
colorParam = ['Y', 'Cb', 'Cr']
26e2fe9f   Chunk   MPB steganalysis ...
33
colorMap = {'Y': 0, 'Cb': 1, 'Cr': 2}
6cbb3879   Chunk   F4 updated.
34

2b474806   Chunk   init.
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# The JPEG class
# ==============

class Jpeg(Jsteg):
    """
      The jpeg (derived from jpegObject) allows the user to extract
      a sequence of pseudo-randomly ordered jpeg coefficients for
      watermarking/steganography, and reinsert them.
    """

    def __init__(self, file=None, key=None, rndkey=True, image=None,
                 verbosity=1, **kw):
        """
          The constructor will return a new Object with data from the given file.

          The key is used to determine the order of the jpeg coefficients.
          If no key is given, a random key is extracted using
          random.SystemRandom().
        """
        if image != None:
            raise NotImplementedError, "Compression is not yet implemented"
        Jsteg.__init__(self, file, **kw)
        self.verbosity = verbosity
        if verbosity > 0:
873557f9   Chunk   staged.
59
            print "[Jpeg.__init__] Image size %ix%i" % (self.image_width, self.image_height)
2b474806   Chunk   init.
60
61
62
63
64
65
66
        if key != None:
            self.key = key
        elif rndkey:
            self.key = [base.sysrnd.getrandbits(16) for x in range(16)]
        else:
            self.key = None

26e2fe9f   Chunk   MPB steganalysis ...
67

2b474806   Chunk   init.
68
69
70
71
72
73
74
    def getkey(self):
        """Return the key used to shuffle the coefficients."""
        return self.key

    # 1D Signal Representations
    # -------------------------

6cbb3879   Chunk   F4 updated.
75
    def rawsignal(self, mask=base.acMaskBlock, channel="All"):
2b474806   Chunk   init.
76
77
78
79
80
        """
          Return a 1D array of AC coefficients.
          (Most applications should use getsignal() rather than rawsignal().)
        """
        R = []
6cbb3879   Chunk   F4 updated.
81
82
83
84
85
86
87
88
        if channel == "All":
            for X in self.coef_arrays:
                (h, w) = X.shape
                A = base.acMask(h, w, mask)
                R = np.hstack([R, X[A]])
        else:
            cID = self.getCompID(channel)
            X = self.coef_arrays[cID]
2b474806   Chunk   init.
89
90
91
92
93
            (h, w) = X.shape
            A = base.acMask(h, w, mask)
            R = np.hstack([R, X[A]])
        return R

6cbb3879   Chunk   F4 updated.
94
    def getsignal(self, mask=base.acMaskBlock, channel="All"):
2b474806   Chunk   init.
95
        """Return a 1D array of AC coefficients in random order."""
6cbb3879   Chunk   F4 updated.
96
        R = self.rawsignal(mask, channel)
2b474806   Chunk   init.
97
98
99
100
101
102
        if self.key == None:
            return R
        else:
            rnd.seed(self.key)
            return R[rnd.permutation(len(R))]

6cbb3879   Chunk   F4 updated.
103
    def setsignal(self, R0, mask=base.acMaskBlock, channel="All"):
2b474806   Chunk   init.
104
105
106
107
108
109
110
111
112
        """Reinserts AC coefficients from getitem in the correct positions."""
        if self.key != None:
            rnd.seed(self.key)
            fst = 0
            P = rnd.permutation(len(R0))
            R = np.array(R0)
            R[P] = R0
        else:
            R = R0
6cbb3879   Chunk   F4 updated.
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
        if channel == "All":
            for cID in range(3):
                X = self.coef_arrays[cID]
                s = X.size * 63 / 64
                (h, w) = X.shape
                X[base.acMask(h, w, mask)] = R[fst:(fst + s)]
                fst += s

                # Jset
                blocks = self.getCoefBlocks(channel=colorParam[cID])
                xmax, ymax = self.Jgetcompdim(cID)
                for y in range(ymax):
                    for x in range(xmax):
                        block = blocks[y, x]
                        self.Jsetblock(x, y, cID, bytearray(block.astype(np.int16)))

        else:
            cID = self.getCompID(channel)
            X = self.coef_arrays[cID]
2b474806   Chunk   init.
132
133
134
135
            s = X.size * 63 / 64
            (h, w) = X.shape
            X[base.acMask(h, w, mask)] = R[fst:(fst + s)]
            fst += s
6cbb3879   Chunk   F4 updated.
136
137
138
139
140
141
142
143
144

            # Jset
            blocks = self.getCoefBlocks(channel)
            xmax, ymax = self.Jgetcompdim(cID)
            for y in range(ymax):
                for x in range(xmax):
                    block = blocks[y, x]
                    self.Jsetblock(x, y, cID, bytearray(block.astype(np.int16)))

2b474806   Chunk   init.
145
        assert len(R) == fst
6cbb3879   Chunk   F4 updated.
146

2b474806   Chunk   init.
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176

    # Histogram and Image Statistics
    # ------------------------------

    def abshist(self, mask=base.acMaskBlock, T=8):
        """
          Make a histogram of absolute values for a signal.
        """
        A = abs(self.rawsignal(mask)).tolist()
        L = len(A)
        D = {}
        C = 0
        for i in range(T + 1):
            D[i] = A.count(i)
            C += D[i]
        D["high"] = L - C
        D["total"] = L
        return D

    def hist(self, mask=base.acMaskBlock, T=8):
        """
          Make a histogram of the jpeg coefficients.
          The mask is a boolean 8x8 matrix indicating the
          frequencies to be included.  This defaults to the
          AC coefficients.
        """
        A = self.rawsignal(mask).tolist()
        E = [-np.inf] + [i for i in range(-T, T + 2)] + [np.inf]
        return np.histogram(A, E)

548d95dc   Chunk   steganography(F3 ...
177
178
179
180
181
182
183
184
185
186
187
188
    def plotHist(self, mask=base.acMaskBlock, T=8):
        """
          Make a histogram of the jpeg coefficients.
          The mask is a boolean 8x8 matrix indicating the
          frequencies to be included.  This defaults to the
          AC coefficients.
        """
        A = self.rawsignal(mask).tolist()
        E = [i for i in range(-T, T + 2)]
        plt.hist(A, E, histtype='bar')
        plt.show()

2b474806   Chunk   init.
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
    def nzcount(self, *a, **kw):
        """Number of non-zero AC coefficients.

          Arguments are passed to rawsignal(), so a non-default mask could
          be specified to get other coefficients than the 63 AC coefficients.
        """
        R = list(self.rawsignal(*a, **kw))
        return len(R) - R.count(0)

    # Access to JPEG Image Data
    # -------------------------

    def getCompID(self, channel):
        """
          Get the index of the given colour channel.
        """
        # How do we adress different channels?
        colourSpace = self.jpeg_color_space;
        if colourSpace == colorCode["GRAYSCALE"]:
            if channel == "Y":
                return 0
            elif channel == None:
                return 0
            else:
                raise Exception, "Invalid colour space designator"
        elif colourSpace == colorCode["YCbCr"]:
            if channel == "Y":
                return 0
            elif channel == "Cb":
                return 1
            elif channel == "Cr":
                return 2
            else:
                raise Exception, "Invalid colour space designator"
        raise NotImplementedError, "Only YCbCr and Grayscale are supported."

    def getQMatrix(self, channel):
        """
          Return the quantisation matrix for the given colour channel.
        """
        cID = self.getCompID(channel)
        return self.quant_tables[self.comp_info[cID]["quant_tbl_no"]]

    def getCoefMatrix(self, channel="Y"):
        """
          This method returns the coefficient matrix for the given
          colour channel (as a matrix).
        """
        cID = self.getCompID(channel)
        return self.coef_arrays[cID]

fad8d727   Chunk   so you want to se...
240
241
242
243
244
245
246
    def setCoefMatrix(self, matrix, channel="Y"):
        v, h = self.getCoefMatrix(channel).shape
        assert matrix.shape == (v, h), "matrix is expected of size (%d,%d)" % (v, h)

        cID = self.getCompID(channel)
        self.coef_arrays[cID] = matrix

8c310e83   Chunk   jpeg base resolved.
247
248
249
250
251
252
        blocks = self.getCoefBlocks(channel)
        xmax, ymax = self.Jgetcompdim(cID)
        for y in range(ymax):
            for x in range(xmax):
                block = blocks[y, x]
                self.Jsetblock(x, y, cID, bytearray(block.astype(np.int16)))
fad8d727   Chunk   so you want to se...
253

2b474806   Chunk   init.
254
255
256
257
258
    def getCoefBlocks(self, channel="Y"):
        """
          This method returns the coefficient matrix for the given
          colour channel (as a 4-D tensor: (v,h,row,col)).
        """
fad8d727   Chunk   so you want to se...
259
        if channel == "All":
dceec280   Chunk   get capacity.
260
261
262
            return [
                np.array([np.hsplit(arr, arr.shape[1] / 8) for arr in np.vsplit(compMat, compMat.shape[0] / 8)])
                for compMat in self.coef_arrays]
fad8d727   Chunk   so you want to se...
263

dceec280   Chunk   get capacity.
264
        compMat = self.getCoefMatrix(channel="Y")
548d95dc   Chunk   steganography(F3 ...
265
        return np.array([np.hsplit(arr, arr.shape[1] / 8) for arr in np.vsplit(compMat, compMat.shape[0] / 8)])
fad8d727   Chunk   so you want to se...
266
267
268
269
270
271
272
273
274
275
276
277
278
279

    def getCoefBlock(self, channel="Y", loc=(0, 0)):
        """
          This method returns the coefficient matrix for the given
          colour channel (as a 4-D tensor: (v,h,row,col)).
        """
        return self.getCoefBlocks(channel)[loc]


    def setCoefBlock(self, block, channel="Y", loc=(0, 0)):
        assert block.shape == (8, 8), "block is expected of size (8,8)"
        cID = self.getCompID(channel)
        v, h = loc[0] * 8, loc[1] * 8
        self.coef_arrays[cID][v:v + 8, h:h + 8] = block
2b474806   Chunk   init.
280

8c310e83   Chunk   jpeg base resolved.
281
282
        self.Jsetblock(loc[1], loc[0], cID, bytearray(block.astype(np.int16)))

548d95dc   Chunk   steganography(F3 ...
283
284
285
286
    def setCoefBlocks(self, blocks, channel="Y"):
        assert blocks.shape[-2:] == (8, 8), "block is expected of size (8,8)"
        cID = self.getCompID(channel)

6cbb3879   Chunk   F4 updated.
287
        vmax, hmax = blocks.shape[:2]
548d95dc   Chunk   steganography(F3 ...
288
289
290
        for i in range(vmax):
            for j in range(hmax):
                v, h = i * 8, j * 8
6cbb3879   Chunk   F4 updated.
291
292
                self.coef_arrays[cID][v:v + 8, h:h + 8] = blocks[i, j]
                self.Jsetblock(j, i, cID, bytearray(blocks[i, j].astype(np.int16)))
548d95dc   Chunk   steganography(F3 ...
293

f4b5291c   Chunk   Qaulity Calculati...
294
295
296
    def getSize(self):
        return self.image_width, self.image_height

dceec280   Chunk   get capacity.
297
298
299
300
301
302
303
304
    def getQuality(self):
        """
        Qaulity rating algorithm from ImageMagick.

            e.g.
            find ./ -name "*.jpg" | xargs -i sh -c "echo -n {} && identify -quiet -verbose {} |grep -E 'Quality' "

        Ref - http://stackoverflow.com/questions/2024947/is-it-possible-to-tell-the-quality-level-of-a-jpeg,http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=20235
f4b5291c   Chunk   Qaulity Calculati...
305
306
307
308
309
310
311
312
313
        """
        table0 = self.quant_tables[0].ravel()
        table1 = self.quant_tables[1].ravel()
        sum0 = np.sum(table0)
        sum1 = np.sum(table1)
        quality = None

        if sum0 != None:
            if sum1 != None:
4a20967b   Chunk   staged.
314
315
                sum = sum0 + sum1
                qvalue = table0[2] + table0[53] + table1[0] + table1[-1]
f4b5291c   Chunk   Qaulity Calculati...
316
317
318
319
320
                hashtable = bi_hash
                sumtable = bi_sum
            else:
                sum = sum0
                qvalue = table0[2] + table0[53]
873557f9   Chunk   staged.
321
322
                hashtable = single_hash
                sumtable = single_sum
f4b5291c   Chunk   Qaulity Calculati...
323
324
325
326
        else:
            raise Exception("Quantization Tables Illegal")
            return None

4a20967b   Chunk   staged.
327
        for i in range(100):
f4b5291c   Chunk   Qaulity Calculati...
328
329
330
331
332
333
334
335
336
337
338
339
340
341
            if qvalue >= hashtable[i] or sum >= sumtable[i]:
                break
        quality = i + 1

        return quality


    # Decompression
    # -------------

    def getSpatial(self, channel="Y"):
        """
          This method returns one decompressed colour channel as a matrix.
          The appropriate JPEG coefficient matrix is dequantised
2b474806   Chunk   init.
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
          (using the quantisation tables held by the object) and
          inverse DCT transformed.
        """
        X = self.getCoefMatrix(channel)
        Q = self.getQMatrix(channel)
        (M, N) = shape(X)
        assert M % 8 == 0, "Image size not divisible by 8"
        assert N % 8 == 0, "Image size not divisible by 8"
        D = X * base.repmat(Q, (M / 8, N / 8))
        S = ibdct(D)
        # assert max( abs(S).flatten() ) <=128, "Image colours out of range"
        return (S + 128 ).astype(np.uint8)

    # Complete, general decompression is not yet implemented::

    def getimage(self):
        """
          Decompress the image and a PIL Image object.
        """

        # Probably better to use a numpy image/array.

        raise NotImplementedError, "Decompression is not yet implemented"

        # We miss the routines for upsampling and adjusting the size

        L = len(self.coef_arrays)
        im = []
        for i in range(L):
            C = self.coef_arrays[i]
            if C != None:
                Q = self.quant_tables[self.comp_info[i]["quant_tbl_no"]]
                im.append(ibdct(dequantise(C, Q)))
        return Image.fromarray(im)


    # Calibration
    # -----------

    def getCalibrated(self, channel="Y", mode="all"):
        """
          Return a calibrated coefficient matrix for the given channel.
          Channel may be "Y", "Cb", or "Cr" for YCbCr format.
          For Grayscale images, it may be None or "Y".
        """
        S = self.getSpatial(channel)
        (M, N) = shape(S)
        assert M % 8 == 0, "Image size not divisible by 8"
        assert N % 8 == 0, "Image size not divisible by 8"
        if mode == "col":
            S1 = S[:, 4:(N - 4)]
            cShape = ( M / 8, N / 8 - 1 )
        else:
            S1 = S[4:(M - 4), 4:(N - 4)]
            cShape = ( (M - 1) / 8, (N - 1) / 8 )
        D = bdct(S1 - 128)
        X = D / base.repmat(self.getQMatrix(channel), cShape)
        return np.round(X)

    def calibrate(self, *a, **kw):
        assert len(self.coef_arrays) == 1
        self.coef_arrays[0] = self.getCalibrated(*a, **kw)

    def getCalSpatial(self, channel="Y"):
        """
          Return the decompressed, calibrated, grayscale image.
          A different colour channel can be selected with the channel
          argument.
        """

        # We calibrate the image, obtaining a JPEG matrix.

        C = self.getCalibrated(channel)

        # The rest is straight forward JPEG decompression.

        (M, N) = shape(C)
        cShape = (M / 8, N / 8)
        D = C * base.repmat(self.getQMatrix(channel), cShape)
        S = np.round(ibdct(D) + 128)
        return S.astype(np.uint8)


def diffblock(c1, c2):
    diff = False
    if np.array_equal(c1, c2):
        print("blocks match")
    else:
        print("blocks not match")
8c310e83   Chunk   jpeg base resolved.
431
        diff = True
26e2fe9f   Chunk   MPB steganalysis ...
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447

    return diff


def diffblocks(a, b):
    diff = False
    cnt = 0
    for comp in range(a.image_components):
        xmax, ymax = a.Jgetcompdim(comp)
        for y in range(ymax):
            for x in range(xmax):
                if a.Jgetblock(x, y, comp) != b.Jgetblock(x, y, comp):
                    print("blocks({},{}) in component {} not match".format(y, x, comp))
                    diff = True
                    cnt += 1
    return diff, cnt
8c310e83   Chunk   jpeg base resolved.

f4b5291c   Chunk   Qaulity Calculati...