Amazing-Python-Scripts

Форк
0
607 строк · 12.7 Кб
1
"""
2
IMAGE EDITOR USING PILLOW LIBRARY.
3
"""
4

5
# Importing the image module from pillow library.
6

7
# Importing ImageFilter, ImageEnhance modules from pillow library.
8

9
from PIL import Image, ImageFilter, ImageEnhance
10

11
# Importing system module.
12

13
import sys
14

15
'''
16
============================================================================
17
^^^~~~~~~~~~~~~~~~~~~~~~|||||DEFINED FUNCTIONS|||||~~~~~~~~~~~~~~~~~~~~~~^^^
18
============================================================================
19
'''
20

21
'''
22
============== Function to show available options on CLI ==================
23
'''
24

25

26
def home():
27

28
    print(" --> 1. Flip the image.")
29

30
    print(" --> 2. Rotate the image by 90 degrees.")
31

32
    print(" --> 3. Rotate the image by 180 degrees")
33

34
    print(" --> 4. Blur the image")
35

36
    print(" --> 5. Embossed image")
37

38
    print(" --> 6. Apply more filters")
39

40
    print(" --> 7. Contrast adjustments")
41

42
    print(" --> 8. Increase sharpness")
43

44
    print(" --> 9. quit")
45

46
    print(" ")
47

48

49
'''
50
======================== Function to save edited image ========================
51
'''
52

53

54
# This function will ask the user if he wants the edited file to be saved
55

56
def saving_edited_image():
57

58
    print("========Do you want to save the edited image ?==========")
59

60
    saving_choice = input("Type 1 for YES and 2 for NO : ")
61

62
    if saving_choice in ("1", "2"):
63

64
        if saving_choice == '1':
65

66
            path_specified = input(r"===== Enter the path where you"
67
                                   r" want to store the edited image."
68
                                   r"also mention the name of image "
69
                                   r"with extension=====")
70

71
            # saving the image at given path
72

73
            im.save(path_specified)
74

75
            # final message after saving the image
76

77
            print("====Image changes done and saved !! Keep editing====")
78

79
        if saving_choice == '2':
80

81
            # back to the main menu
82

83
            print("~~~Back to the main menu~~~")
84

85
            main()
86

87
    else:
88

89
        '''
90
        if the user inputs value other than the specified ones,
91
        this function will be called again.
92
        '''
93

94
        print("=====!!! PLEASE CHOOSE FROM SPECIFIED OPTIONS !!!=====")
95

96
        saving_edited_image()
97

98

99
'''
100
================== Function for edited image preview =======================
101
'''
102

103

104
'''
105
this function will ask the user if he wants a
106
preview of edited image or not and will provide the same
107
'''
108

109

110
def edited_image_preview(image_name):
111

112
    print("=======Do you want to preview the edited image ?=======")
113

114
    preview_choice = input("Type 1 for YES and 2 for NO : ")
115

116
    if preview_choice in ('1', '2'):
117

118
        if preview_choice == '1':
119

120
            # this will show the edited image for the user to review
121

122
            image_name.show()
123

124
            # function to save the image is called
125

126
            saving_edited_image()
127

128
        if preview_choice == '2':
129
            # function to save the image is again called
130

131
            saving_edited_image()
132

133
    else:
134

135
        print("=====!!! PLEASE CHOOSE FROM SPECIFIED OPTIONS !!!=====")
136

137
        edited_image_preview(image_name)
138

139

140
'''
141
====================== Function to flip image =====================
142
'''
143

144

145
def flip():
146

147
    flipped_image = im.transpose(Image.FLIP_LEFT_RIGHT)
148

149
    # function to preview edited image is called
150

151
    edited_image_preview(flipped_image)
152

153

154
'''
155
=================== Function to rotate image by 90 degrees =================
156
'''
157

158

159
def rotate_90():
160

161
    rotated_image_90 = im.transpose(Image.ROTATE_90)
162

163
    # function to preview edited image is called
164

165
    edited_image_preview(rotated_image_90)
166

167

168
'''
169
================ Function to rotate image by 180 image ============
170
'''
171

172

173
def rotate_180():
174

175
    rotated_image_180 = im.transpose(Image.ROTATE_180)
176

177
    # function to preview edited image is called
178

179
    edited_image_preview(rotated_image_180)
180

181

182
'''================= function to blur the image ==================='''
183

184

185
def blur():
186

187
    blur_image = im.filter(ImageFilter.BLUR)
188

189
    # function to preview edited image is called
190

191
    edited_image_preview(blur_image)
192

193

194
'''================== Function to emboss the image =================='''
195

196

197
def embossing():
198

199
    emboss_image = im.filter(ImageFilter.EMBOSS)
200

201
    # function to preview edited image is called
202

203
    edited_image_preview(emboss_image)
204

205

206
'''================ Function to sharpen the image ====================='''
207

208

209
def sharpen():
210

211
    sharpness_enhancer = ImageEnhance.Sharpness(im)
212

213
    sharpened_image = sharpness_enhancer.enhance(5)
214

215
    # function to preview edited image is called
216

217
    edited_image_preview(sharpened_image)
218

219

220
'''============= Function for changing the contrast ================='''
221

222

223
# this is the function to increase or decrease the contrast of the image
224

225
def contrast():
226

227
    print("Actions available : ")
228

229
    print("--> 1. Increase contrast")
230

231
    print("--> 2. Decrease contrast")
232

233
    print("--> 3. Main menu")
234

235
    contrast_choice = input("CHOOSE ACTION TO TAKE : ")
236

237
    if contrast_choice in ('1', '2', '3'):
238

239
        if contrast_choice == '1':
240

241
            # increasing the contrast of the image by specifying factor of 2
242

243
            contrast_enhancer = ImageEnhance.Contrast(im)
244

245
            inc_contrast = contrast_enhancer.enhance(2)
246

247
            # function to preview edited image is called
248

249
            edited_image_preview(inc_contrast)
250

251
        elif contrast_choice == '2':
252

253
            # decreasing the contrast of the image by specifying factor of 0.5
254

255
            contrast_decrease = ImageEnhance.Contrast(im)
256

257
            dec_contrast = contrast_decrease.enhance(0.5)
258

259
            # function to preview edited image is called
260

261
            edited_image_preview(dec_contrast)
262

263
        elif contrast_choice == '3':
264

265
            # function to load main menu is called
266

267
            main()
268

269
    else:
270
        print("=====!!! PLEASE CHOOSE FROM SPECIFIED OPTIONS !!!=====")
271

272
        '''
273
        if the user won't chose from the specified options, this function will
274
        be called again unless and until user chooses from specified options
275
        '''
276

277
        contrast()
278

279

280
'''
281
=============Function to show available filter options on CLI=================
282
'''
283

284

285
def filter_options():
286

287
    print("--> 1. Black And White")
288

289
    print("--> 2. Sepia")
290

291
    print("--> 3. Negative")
292

293
    print("--> 4. Rust")
294

295
    print("--> 5. Canary Yellow")
296

297
    print("--> 6. Dracula")
298

299
    print("--> 7. Mystic Meadows")
300

301
    print("--> 8. Back to main menu")
302

303

304
'''
305
=========Functions containing different RGB values for different filters=======
306
'''
307

308
'''
309
- these are the functions defined for different filters
310

311
- new_red, new_green, new_blue will store the modified
312
  r, g, b values of the image
313
'''
314

315
# function for black and white filter
316

317

318
def black_n_white(r, g, b):
319
    """
320
    changing r, g, b values according to filter
321
    and storing them in new_red, new_green, new_blue
322
    """
323

324
    new_red = (r + g + b) // 3
325

326
    new_green = (r + g + b) // 3
327

328
    new_blue = (r + g + b) // 3
329

330
    return new_red, new_green, new_blue
331

332

333
# function for sepia filter
334

335
def sepia(r, g, b):
336

337
    new_red = int((r * .393) + (g * .769) + (b * .189))
338

339
    new_green = int((r * .349) + (g * .686) + (b * .168))
340

341
    new_blue = int((r * .272) + (g * .534) + (b * .131))
342

343
    return new_red, new_green, new_blue
344

345

346
# function for negative filter
347

348
def negative(r, g, b):
349

350
    new_red = 255 - r
351

352
    new_green = 255 - g
353

354
    new_blue = 255 - b
355

356
    return new_red, new_green, new_blue
357

358

359
# function for rust filter
360

361
def rust(r, g, b):
362

363
    new_red = (r + g + b) // 2
364

365
    new_green = (r + g + b) // 4
366

367
    new_blue = (r + g + b) // 6
368

369
    return new_red, new_green, new_blue
370

371

372
# function for canary_yellow
373

374
def canary_yellow(r, g, b):
375

376
    new_red = r
377

378
    new_green = r + g*0
379

380
    new_blue = b
381

382
    return new_red, new_green, new_blue
383

384

385
# function for dracula filter
386

387
def dracula(r, g, b):
388

389
    new_red = (r + g + b) // 2
390

391
    new_green = g // 2
392

393
    new_blue = b // 2
394

395
    return new_red, new_green, new_blue
396

397

398
# function for mystic meadows filter
399

400
def mystic(r, g, b):
401

402
    new_red = r
403

404
    new_green = g
405

406
    new_blue = g + b*0
407

408
    return new_red, new_green, new_blue
409

410

411
'''
412
==========Function for the filter selection submenu==========
413
'''
414

415

416
def submenu_filters():
417
    # printing all filter options
418

419
    filter_options()
420

421
    # asking the user to choose a filter to apply
422

423
    filter_choice = input("Enter what filter would you "
424
                          "like to apply(1, 2, 3, 4, 5, 6, 7, 8 : ")
425

426
    if filter_choice in ('1', '2', '3', '4', '5', '6', '7', '8'):
427

428
        '''
429
        iterating over the pixels of the image
430
        present in y axis(height) and x axis(width)
431
        '''
432

433
        for pixel_y in range(height):
434

435
            for pixel_x in range(width):
436

437
                '''
438
                loading rgb values of pixels at
439
                x and y coordinates into r, g, b
440
                '''
441

442
                r, g, b = im.getpixel((pixel_x, pixel_y))
443

444
                if filter_choice == '1':
445

446
                    # function to apply black and white filter is called
447

448
                    pixels[pixel_x, pixel_y] = black_n_white(r, g,
449
                                                             b)
450
                elif filter_choice == '2':
451

452
                    # function to apply sepia filter is called
453

454
                    pixels[pixel_x, pixel_y] = sepia(r, g, b)
455

456
                elif filter_choice == '3':
457

458
                    # function to apply negative filter is called
459

460
                    pixels[pixel_x, pixel_y] = negative(r, g, b)
461

462
                elif filter_choice == '4':
463

464
                    # function to apply rust filter is called
465

466
                    pixels[pixel_x, pixel_y] = rust(r, g, b)
467

468
                elif filter_choice == '5':
469

470
                    # function to apply canary yellow filter is called
471

472
                    pixels[pixel_x, pixel_y] = canary_yellow(r, g,
473
                                                             b)
474

475
                elif filter_choice == '6':
476

477
                    # function to apply dracula filter is called
478

479
                    pixels[pixel_x, pixel_y] = dracula(r, g, b)
480

481
                elif filter_choice == '7':
482

483
                    # function to apply mystic meadows filter is called
484

485
                    pixels[pixel_x, pixel_y] = mystic(r, g, b)
486

487
                elif filter_choice == '8':
488

489
                    # for going back to main menu main function is called
490

491
                    main()
492

493
        # to view and save the edited image edited_image_preview is called
494

495
        edited_image_preview(im)
496

497
    else:
498

499
        print("=====!!! PLEASE CHOOSE FROM SPECIFIED OPTIONS !!!=====")
500

501
        '''
502
         if the user won't chose from the specified options,
503
         this function will be called again unless and until
504
         user chooses from specified options
505
        '''
506
        submenu_filters()
507

508

509
'''
510
====================== MAIN MENU =========================
511
'''
512

513

514
def main():
515

516
    while True:
517

518
        # showing list of operations to be performed on the image onto the CLI
519

520
        home()
521

522
        choice = input("Choose the action you want to "
523
                       "take (1,2,3,4,5,6,7,8,9) : ")
524

525
        if choice in ('1', '2', '3', '4', '5', '6', '7', '8', '9'):
526

527
            if choice == '1':
528
                flip()
529

530
            if choice == '2':
531
                rotate_90()
532

533
            if choice == '3':
534
                rotate_180()
535

536
            if choice == '4':
537
                blur()
538

539
            if choice == '5':
540
                embossing()
541

542
            if choice == '6':
543
                submenu_filters()
544

545
            if choice == '7':
546
                contrast()
547

548
            if choice == '8':
549
                sharpen()
550

551
            if choice == '9':
552

553
                # final message as the program is closed
554

555
                print("Thanks for using Image editor")
556

557
                sys.exit()  # terminates the program
558

559
        else:
560

561
            print("=====!!! PLEASE CHOOSE FROM SPECIFIED OPTIONS !!!=====")
562

563
            main()
564

565

566
'''======================================================================'''
567

568
print("=" * 22 + "IMAGE EDITOR SCRIPT" + "=" * 22)
569

570
print("==INSTRUCTIONS==")
571

572
print(" # Welcome to the image editing script.")
573

574
print(" # Start by entering the path of the image to be edited")
575

576
print(" # The path must include the image name along with the extension.")
577

578
print(" # Choose from the given editing options.")
579

580
print(" # Save the image by specifying the path and the new image name "
581
      "along with extension.")
582

583
print(" ")
584

585
print("="*50)
586

587
# Taking path of image from the user
588

589
image_input = input(r"Enter the path of the image to be edited : ")
590

591
# creating an image object im
592

593
# converting image into RGB and loading it into im
594

595
im = Image.open(image_input).convert("RGB")
596

597
# im.size stores the width and height of the image in the tuple
598

599
width, height = im.size
600

601
pixels = im.load()
602

603
# Calling main function
604

605
main()
606

607
'''=========================================================='''
608

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.