Python
2019.07.17 15:01

Image 기반 Steganography 예제

조회 수 28149 댓글 1
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print


https://www.geeksforgeeks.org/image-based-steganography-using-python/



[Python 3]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# Python program implementing Image Steganography
 
# PIL module is used to extract
# pixels of image and modify it
from PIL import Image
 
# Convert encoding data into 8-bit binary
# form using ASCII value of characters
def genData(data):
         
        # list of binary codes
        # of given data
        newd = []
         
        for i in data:
            newd.append(format(ord(i), '08b'))
        return newd
         
# Pixels are modified according to the
# 8-bit binary data and finally returned
def modPix(pix, data):
     
    datalist = genData(data)
    lendata = len(datalist)
    imdata = iter(pix)
 
    for i in range(lendata):
         
        # Extracting 3 pixels at a time
        pix = [value for value in imdata.__next__()[:3] +
                                imdata.__next__()[:3] +
                                imdata.__next__()[:3]]
                                     
        # Pixel value should be made
        # odd for 1 and even for 0
        for j in range(0, 8):
            if (datalist[i][j]=='0') and (pix[j]% 2 != 0):
                 
                if (pix[j]% 2 != 0):
                    pix[j] -= 1
                     
            elif (datalist[i][j] == '1') and (pix[j] % 2 == 0):
                pix[j] -= 1
                 
        # Eigh^th pixel of every set tells
        # whether to stop ot read further.
        # 0 means keep reading; 1 means the
        # message is over.
        if (i == lendata - 1):
            if (pix[-1] % 2 == 0):
                pix[-1] -= 1
        else:
            if (pix[-1] % 2 != 0):
                pix[-1] -= 1
 
        pix = tuple(pix)
        yield pix[0:3]
        yield pix[3:6]
        yield pix[6:9]
 
def encode_enc(newimg, data):
    w = newimg.size[0]
    (x, y) = (0, 0)
     
    for pixel in modPix(newimg.getdata(), data):
         
        # Putting modified pixels in the new image
        newimg.putpixel((x, y), pixel)
        if (x == w - 1):
            x = 0
            y += 1
        else:
            x += 1
             
# Encode data into image
def encode():
    img = input("Enter image name(with extension): ")
    image = Image.open(img, 'r')
     
    data = input("Enter data to be encoded : ")
    if (len(data) == 0):
        raise ValueError('Data is empty')
         
    newimg = image.copy()
    encode_enc(newimg, data)
     
    new_img_name = input("Enter the name of new image(with extension): ")
    newimg.save(new_img_name, str(new_img_name.split(".")[1].upper()))
 
# Decode the data in the image
def decode():
    img = input("Enter image name(with extension) :")
    image = Image.open(img, 'r')
     
    data = ''
    imgdata = iter(image.getdata())
     
    while (True):
        pixels = [value for value in imgdata.__next__()[:3] +
                                imgdata.__next__()[:3] +
                                imgdata.__next__()[:3]]
        # string of binary data
        binstr = ''
         
        for i in pixels[:8]:
            if (i % 2 == 0):
                binstr += '0'
            else:
                binstr += '1'
                 
        data += chr(int(binstr, 2))
        if (pixels[-1] % 2 != 0):
            return data
             
# Main Function     
def main():
    a = int(input(":: Welcome to Steganography ::\n"
                        "1. Encode\n 2. Decode\n"))
    if (a == 1):
        encode()
         
    elif (a == 2):
        print("Decoded word- " + decode())
    else:
        raise Exception("Enter correct input")
         
# Driver Code
if __name__ == '__main__' :
     
    # Calling main function
    main()



[Python 2]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# Python program implementing Image Steganography
 
# PIL module is used to extract
# pixels of image and modify it
from PIL import Image
import sys, os
 
# Convert encoding data into 8-bit binary
# form using ASCII value of characters
def genData(data):
    # list of binary codes
    # of given data
    newd = []
 
    for i in data:
        newd.append(format(ord(i), '08b'))
    return newd
 
 
# Pixels are modified according to the
# 8-bit binary data and finally returned
def modPix(pix, data):
    datalist = genData(data)
    lendata = len(datalist)
    imdata = iter(pix)
 
    for i in range(lendata):
 
        # Extracting 3 pixels at a time
        pix = [value for value in imdata.next()[:3] +
               imdata.next()[:3] +
               imdata.next()[:3]]
 
        # Pixel value should be made
        # odd for 1 and even for 0
        for j in range(0, 8):
            if (datalist[i][j] == '0') and (pix[j] % 2 != 0):
 
                if (pix[j] % 2 != 0):
                    pix[j] -= 1
 
            elif (datalist[i][j] == '1') and (pix[j] % 2 == 0):
                pix[j] -= 1
 
        # Eigh^th pixel of every set tells
        # whether to stop ot read further.
        # 0 means keep reading; 1 means the
        # message is over.
        if (i == lendata - 1):
            if (pix[-1] % 2 == 0):
                pix[-1] -= 1
        else:
            if (pix[-1] % 2 != 0):
                pix[-1] -= 1
 
        pix = tuple(pix)
        yield pix[0:3]
        yield pix[3:6]
        yield pix[6:9]
 
 
def encode_enc(newimg, data):
    w = newimg.size[0]
    (x, y) = (0, 0)
 
    for pixel in modPix(newimg.getdata(), data):
 
        # Putting modified pixels in the new image
        newimg.putpixel((x, y), pixel)
        if (x == w - 1):
            x = 0
            y += 1
        else:
            x += 1
 
 
# Encode data into image
def encode(orgfilename, msg, outfilename):
    img = orgfilename
    image = Image.open(img, 'r')
 
    data = msg
    if (len(data) == 0):
        raise ValueError('Data is empty')
 
    newimg = image.copy()
    encode_enc(newimg, data)
 
    new_img_name = outfilename
    newimg.save(new_img_name, str(new_img_name.split(".")[1].upper()))
 
 
# Decode the data in the image
def decode(filename):
    img = filename
    image = Image.open(img, 'r')
 
    data = ''
    imgdata = iter(image.getdata())
 
    while (True):
        pixels = [value for value in imgdata.next()[:3] +
                  imgdata.next()[:3] +
                  imgdata.next()[:3]]
        # string of binary data
        binstr = ''
 
        for i in pixels[:8]:
            if (i % 2 == 0):
                binstr += '0'
            else:
                binstr += '1'
 
        data += chr(int(binstr, 2))
        if (pixels[-1] % 2 != 0):
            print data
            return data
 
        # Main Function
 
def printUsage():
    print " This program Encode / Decode hidden message into image."
    print " <Usage>"
    print "   Encode: steg_test.py -a [input_filename] [message] [out_filename]"
    print "   Decode: steg_test.py -b [out_filename]"
 
if __name__ == '__main__':
    if len(sys.argv) < 3:
        printUsage()
        exit(0)
 
    if sys.argv[1] == '-a':
        if len(sys.argv) == 5:
            encode(sys.argv[2], sys.argv[3], sys.argv[4])
        else:
            printUsage()
    elif sys.argv[1] == '-b':
        if len(sys.argv) == 3:
            decode(sys.argv[2])
        else:
            printUsage()
    else:
        printUsage()



Dreamy의 코드 스크랩

내가 모으고 내가 보는

List of Articles
번호 분류 제목 날짜 조회 수 추천 수
480 Android 안드로이드 국가별 언어코드 2020.10.06 7320 0
479 Android Android Studio 안드로이드 스튜디오 단축키 2020.03.16 6071 0
478 일반 전기적 스펙에 관한 용어, 약자 정리 2020.02.24 7567 0
477 PHP SQL 일정 시간단위로 데이터 검색하기 2020.02.12 7371 0
476 LINUX Ubuntu php5.6 , php7.1 설치 및 셋팅하기 2020.02.11 8265 0
475 LINUX Ubuntu apt-get 명령어 정리 2020.02.11 6555 0
474 LINUX 우분투(Ubuntu) 설치된 패키지 목록 확인하기 2020.02.11 23530 0
473 일반 온습도, 미세먼지 정보 받아오기 secret 2020.01.10 0 0
472 Pi 아두이노 데이터 저장하기(Arduino EEPROM 사용하기) 2019.12.24 20771 0
471 LINUX mutt Gmail 설치, 사용 / Ubuntu 18.04 환경 2019.11.25 7713 0
470 LINUX 리눅스 명령행에서 메일 보내기(send mail from linux command line) 2019.11.25 11488 0
469 LINUX Ubuntu TFTP 서버 2019.10.30 9830 0
468 Pi 레귤레이터(3.3V 1A) KA78R33 데이터시트 file 2019.08.20 6381 0
467 Pi 회로부품 메모 1 secret 2019.08.09 1 0
466 Pi OP AMP의 활용 2019.08.05 12541 0
목록
Board Pagination ‹ Prev 1 2 3 4 5 6 7 8 9 10 ... 34 Next ›
/ 34

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소

Designed by sketchbooks.co.kr / sketchbook5 board skin

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

불러오는 중···