SiFasik | Free Education For Everyone: Python

Berisi Hal Terkait Tips and Trick, Game, Download, Teknologi dan Sains. Education Blog/Blog edukasi, Edukasi gratis untuk semua orang, Free education for everyone, Stream anime 480p Tanpa Iklan!!.

Source Code Konversi Image To Ascii di Python

Source Code Konversi Image To Ascii di Python

Source Code Konversi Image To Ascii 



Pada postingan kali ini, saya akan membagikan source code program sederhana untuk mengkonversi atau convert gambar menjadi sebuah teks ASCII atau bisa jadi Teks biasa tinggal ubah beberapa source code saja, program ini menurut saya sedikit rumit, dan mungkin bisa dijadikan untuk referensi project tugas sekolah kalian, script ini menggunakan python sebagai bahasanya, langsung saja kita intip source code python nya.

Source code:

import sys, random, argparse
import numpy as np
import math
 
from PIL import Image
 
# 70 levels of gray
gscale1 = "[email protected]%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "
# 10 levels of gray
gscale2 = '@%#*+=-:. '
def getAverageL(image):
    """
    Given PIL Image, return average value of grayscale value
    """
    # get image as numpy array
    im = np.array(image)
    # get the dimensions
    w,h = im.shape
    # get the average
    return np.average(im.reshape(w*h))
 
def covertImageToAscii(fileName, cols, scale, moreLevels):
    """
    Given Image and dimensions (rows, cols), returns an m*n list of Images
    """
    # declare globals
    global gscale1, gscale2
    # open image and convert to grayscale
    image = Image.open(fileName).convert('L')
    # store the image dimensions
    W, H = image.size[0], image.size[1]
    print("input image dims: %d x %d" % (W, H))
    # compute tile width
    w = W/cols
    # compute tile height based on the aspect ratio and scale of the font
    h = w/scale
    # compute number of rows to use in the final grid
    rows = int(H/h)
 
    print("cols: %d, rows: %d" % (cols, rows))
    print("tile dims: %d x %d" % (w, h))
 
    # check if image size is too small
    if cols > W or rows > H:
        print("Image too small for specified cols!")
        exit(0)
 
    # an ASCII image is a list of character strings
    aimg = []
    # generate the list of tile dimensions
    for j in range(rows):
        y1 = int(j*h)
        y2 = int((j+1)*h)
        # correct the last tile
        if j == rows-1:
            y2 = H
        # append an empty string
        aimg.append("")
        for i in range(cols):
            # crop the image to fit the tile
            x1 = int(i*w)
            x2 = int((i+1)*w)
            # correct the last tile
            if i == cols-1:
                x2 = W
            # crop the image to extract the tile into another Image object
            img = image.crop((x1, y1, x2, y2))
            # get the average luminance
            avg = int(getAverageL(img))
            # look up the ASCII character for grayscale value (avg)
            if moreLevels:
                gsval = gscale1[int((avg*69)/255)]
            else:
                gsval = gscale2[int((avg*9)/255)]
            # append the ASCII character to the string
            aimg[j] += gsval
 
    # return text image
    return aimg
 
    # main() function
def main():
    # create parser
    descStr = "This program converts an image into ASCII art."
    parser = argparse.ArgumentParser(description=descStr)
    # add expected arguments
    parser.add_argument('--file', dest='imgFile', required=True)
    parser.add_argument('--scale', dest='scale', required=False)
    parser.add_argument('--out', dest='outFile', required=False)
    parser.add_argument('--cols', dest='cols', required=False)
    parser.add_argument('--morelevels', dest='moreLevels', action='store_true')
 
    # parse arguments
    args = parser.parse_args()
 
    imgFile = args.imgFile
    # set output file
    outFile = 'out.txt'
    if args.outFile:
        outFile = args.outFile
    # set scale default as 0.43, which suits a Courier font
    scale = 0.43
    if args.scale:
        scale = float(args.scale)
    # set cols
    cols = 80
    if args.cols:
        cols = int(args.cols)
    print('generating ASCII art...')
    # convert image to ASCII text
    aimg = covertImageToAscii(imgFile, cols, scale, args.moreLevels)
 
    # open a new text file
    f = open(outFile, 'w')
    # write each string in the list to the new file
    for row in aimg:
        f.write(row + '\n')
    # clean up
    f.close()
    print("ASCII art written to %s" % outFile)
 
# call main
if __name__ == '__main__':
    main()


Untuk menjalankannya, cukup simple pertama, save source code didalam satu folder, lalu bikin folder baru dengan nama terserah kalian, dalam post ini saya akan menamakan folder baru sebagai data. untuk contohnya, bisa dilihat pada gambar dibawah ini


setelah itu masukkan foto yang ingin kalian jadikan ASCII kedalam folder data, sehingga folder data berisi foto, pastikan foto berformat JPG agar maksimal, contohnya seperti dibawah.


ketika sudah seperti itu tinggal jalankan program python tersebut menggunakan cmd atau command prompt dengan command seperti berikut


python AsciiIMG.py --file data/qoobe.jpg --cols 250


sesuaikan file anda, untuk --cols digunakan untuk seberapa detail Gambar diubah kedalam ASCII, gunakan seperlunya, karena semakin besar makan akan semakin lama dan juga berat, berikut contoh command di cmd


setelah seperti itu, buka file out.txt di folder yang sama dengan file python dan lihat hasilnya.

cukup itu saja postingan kali ini, jika ada pertanyaan atau error silahkan komentar di kolom komentar yang sudah disediakan, terima kasih
Source Code Game Sederhana Snake Python

Source Code Game Sederhana Snake Python

Source Code Game Sederhana Snake Python



Postingan kali ini berisi source code game sederhana uler atau snake menggunakan bahasa pemrograman python.

Source Code:


 
import tkinter as tk
import random
 
 
#### GLOBAL VARIALBES ####
SNAKE_COLOR, FOOD_COLOR= "light green", "red"
BG_COLOR, TEXT_COLOR = "black", "white"
WIDTH = 40 #Width of squares in pixels.
FOOD_WIDTH = WIDTH * 3 / 4 #Width of food squares in pixels.
SPEED = 100 #Milliseconds between redraw.
CUSHION = 1 #Applied so that adjacent squares don't overlap.
SCREEN = WIDTH * 30, WIDTH * 17 #Screen size in pixels.
FONT = "ms 70"
 
MAX_T = 1000 // SPEED * 5 #Max steps until food disappears.
FOOD_PROB = 0.04 #Probability a new food appears at any given step.
CONTROLS = LEFT, RIGHT, UP, DOWN = "Left", "Right", "Up", "Down"
EXIT, CHEAT, RESTART = "Escape", "space", "Return"
 
###############################################################################
 
def apply_cushion(rect_def):
    """
    Adjust bounds of a rectangular definition.
    rect_def: tuple, (x, y, x+width, y+width).
    """
    x0, y0, x1, y1 = rect_def
    return x0 + CUSHION, y0 + CUSHION, x1 - CUSHION, y1 - CUSHION
 
 
class Square(object):
    """
    Controls one section of the snake.
    canvas: tk.Canvas object to draw on.
    rect_def: tuple, (x, y, x+WIDTH, y+WIDTH).
    """
    def __init__(self, canvas, rect_def):
        self.square = canvas.create_rectangle(*rect_def, fill=SNAKE_COLOR)
        self.can, self.rect_def = canvas, rect_def
        self.behind, self.dx, self.dy = False, 1, 0
 
    def draw(self, rect_def):
        dx = rect_def[0] - self.rect_def[0]
        dy = rect_def[1] - self.rect_def[1]
        self.dx = dx if not dx else dx // abs(dx)
        self.dy = dy if not dy else dy // abs(dy)
 
        self.can.coords(self.square, *rect_def)
        self.rect_def = rect_def
        if self.behind:
            r = self.get_behind_rect_def()
            self.behind.draw(r)
 
    def add_behind(self):
        if self.behind:
            self.behind.add_behind()
        else:
            r = self.get_behind_rect_def()
            self.behind = Square(self.can, r)
 
    def get_behind_rect_def(self):
        x0, y0, x1, y1 = self.rect_def
        r = (
            x0 - self.dx * WIDTH, y0 - self.dy * WIDTH,
            x1 - self.dx * WIDTH, y1 - self.dy * WIDTH
        )
        return r
 
    def get(self):
        return self.square
 
    def get_overlapping(self):
        return self.can.find_overlapping(*apply_cushion(self.rect_def))
 
    def intersecting(self, overlapping):
        if self.behind:
            return any((
                self.behind.get() in overlapping,
                self.behind.intersecting(overlapping)
            ))
        else:
            return False
 
 
class Snake(object):
    """
    Controls the movement of the snake.
    canvas: tk.Canvas to draw on.
    """
    def __init__(self, canvas):
        self.x, self.y = 0, 0
        r = self.x, self.y, self.x + WIDTH, self.y + WIDTH
        self.head = Square(canvas, r)
        self.direction = 1, 0
 
    def update(self):
        self.x += WIDTH * self.direction[0]
        self.y += WIDTH * self.direction[1]
        r = self.x, self.y, self.x + WIDTH, self.y + WIDTH
        self.head.draw(r)
 
    def add_behind(self):
        self.head.add_behind()
 
    def get_overlapping(self):
        return self.head.get_overlapping()
 
    def is_valid(self):
        return all((
            not self.head.intersecting(self.get_overlapping()),
            self.x >= 0, self.x + WIDTH <= SCREEN[0],
            self.y >= 0, self.y + WIDTH <= SCREEN[1]
        ))
 
    def change_direction(self, direction):
        """
        direction: LEFT, RIGHT, UP, or DOWN.
        """
        if direction == LEFT: self.direction = -1, 0
        elif direction == RIGHT: self.direction = 1, 0
        elif direction == UP: self.direction = 0, -1
        elif direction == DOWN: self.direction = 0, 1
 
 
class Food(object):
    """
    Stores information about the food on the screen.
    canvas: tk.Canvas object to draw on.
    rect_def: tuple, (x, y, x+w, y+w)
    """
    def __init__(self, canvas, rect_def):
        self.food = canvas.create_rectangle(*rect_def, fill=FOOD_COLOR)
        self.can, self.t = canvas, 0
 
    def update(self):
        self.t += 1
 
    def is_well(self):
        return self.t < MAX_T
 
    def destroy(self):
        self.can.delete(self.food)
 
    def get(self):
        return self.food
 
 
class Game(tk.Frame):
 """
 Controls the game animation.
 master: tk.Tk window.
 """
 def __init__(self, master):
  super().__init__(master)
  self.can = tk.Canvas(self, width=SCREEN[0],
        height=SCREEN[1], bg=BG_COLOR
        )
  self.can.pack()
  self.snake, self.food = Snake(self.can), []
 
  for key in CONTROLS:
   master.bind("<%s>" % key,
      lambda e: self.snake.change_direction(e.keysym)
      )
  master.bind("<%s>" % CHEAT, lambda e: self.snake.add_behind())
  self.master, self.score = master, 1
 
 def next(self):
  self.snake.update()
  if random.random() < FOOD_PROB:
   self.add_food()
 
  overlapping = self.snake.get_overlapping()
  i = 0
  while i < len(self.food):
   f = self.food[i]
   f.update()
   if f.get() in overlapping:
    self.snake.add_behind()
    f.destroy()
    self.food.pop(i)
    self.score += 1
   elif not f.is_well():
    f.destroy()
    self.food.pop(i)
   else:
    i += 1
 
  self.master.title("Snake: %d" % self.score)
  if self.snake.is_valid():
   self.after(SPEED, self.next)
  else:
   self.can.create_text(SCREEN[0] // 2, SCREEN[1] // 2,
         fill=TEXT_COLOR, font=FONT,
         text="Game Over: %d" % self.score
         )
 
 def add_food(self):
  x = random.randint(0, SCREEN[0] - FOOD_WIDTH)
  y = random.randint(0, SCREEN[1] - FOOD_WIDTH)
  r = x, y, x + FOOD_WIDTH, y + FOOD_WIDTH
  if not self.can.find_overlapping(*r):
   self.food.append(Food(self.can, r))
  else:
   self.add_food()
 
 def restart(self):
  self.destroy()
  self.__init__(self.master)
  self.pack()
  self.next()
 
 
def main():
 root = tk.Tk()
 root.title("Snake")
 root.resizable(0, 0)
 frame = Game(root)
 frame.pack()
 root.bind("<%s>" % RESTART, lambda e: frame.restart())
 root.bind("<%s>" % EXIT, lambda e: root.destroy())
 #root.eval('tk::PlaceWindow %s center'%root.winfo_pathname(root.winfo_id()))
 frame.next()
 root.mainloop()
 
if __name__ == "__main__":
    main()
 
itu dia source codenya, bila ada pertanyaan silahkan komentar di tempat yang sudah disediakan
Music Player Dengan Python Sederhana

Music Player Dengan Python Sederhana

Music Player Dengan Python Sederhana



Pada post kali ini, saya akan menshare source code music player sederhana dengan bahasa pemrograman python, source code ini cuma bisa play,next,previous, dan stop song aja, makanya  ini cukup sederhana menurut saya, langsung saja menuju tutorialnya

Install Package pygame dan mutagen

buka cmd terus masukkan perintah di bawah ini

pip install pygame

kalau sudah, tinggal install mutagen, ketikkan perintah seperti dibawah

pip install mutagen


setelah itu kita bikin file pythonnya, source codenya dibawah:

Source Code:

import os
import pygame
from tkinter.filedialog import askdirectory
from tkinter import *
from mutagen.id3 import ID3
root=Tk()
root.minsize(300,300)
#array lagu
listofsongs=[]
realnames=[]
index=0
v=StringVar()
songlabel=Label(root,textvariable=v,width=35)
 
def nextsong(event):
    global index
    index+=1
    pygame.mixer.music.load(listofsongs[index])
    pygame.mixer.music.play()
    updatelabel()
 
def previoussong(event):
    global index
    index-=1
    pygame.mixer.music.load(listofsongs[index])
    pygame.mixer.music.play()
    updatelabel()
 
def stopsong(event):
    pygame.mixer.music.stop()
    v.set("")
    return songname
 
def updatelabel():
    global index
    global songname
    v.set(realnames[index])
    return songname
 
 
 
def directorychooser():
    directory=askdirectory()
    os.chdir(directory)
 
 
    for files in os.listdir(directory):
         if files.endswith(".mp3"):
          realdir=os.path.realpath(files)
          audio=ID3(realdir)
          realnames.append(audio["TIT2"].text[0])
          listofsongs.append(files)
 
 
 
    pygame.mixer.init()
    pygame.mixer.music.load(listofsongs[0])
    pygame.mixer.music.play()
 
directorychooser()
 
label=Label(root,text="Music Player")
label.pack()
 
realnames.reverse()
 
listbox=Listbox(root)
listbox.pack()
 
listofsongs.reverse()
 
for items in realnames:
    listbox.insert(0,items)
 
realnames.reverse()
 
nextbutton=Button(root,text="NEXT SONG")
nextbutton.pack()
 
previousbutton=Button(root,text="PREVIOUS SONG")
previousbutton.pack()
 
stopbutton=Button(root,text="STOP SONG")
stopbutton.pack()
#button-1 artinya klik kiri
#button-2 artinya klik tengah
#button-3 artinya klik kanan
nextbutton.bind("<Button-1>",nextsong)
previousbutton.bind("<Button-1>",previoussong)
stopbutton.bind("<Button-1>",stopsong)
 
songlabel.pack()
 
 
root.mainloop()


kalau sudah tinggal buka cmd terus pilih directory source code disimpan, contoh kalau saya simpen di xampp/htdocs/musicplayer

lalu ketik

python *namafile*.py

contohnya seperti dibawah



pas awal mulai akan diberitahu suruh pilih folder yang isinya .mp3 INGAT!!! ISI FOLDER HARUS .MP3 SAJA, TIDAK BOLEH ADA FILE SELAIN FORMAT .MP3 (MAKE SURE YOU CHOOSE THE FOLDER WHICH CONTAIN .MP3 ONLY, AND DOESN'T CONTAIN ANY FORMAT EXCEPT .MP3)

setelah itu tinggal menikmati saja, sekian post kali ini, jika ada pertanyaan atau error silahkan gunakan kolom komentar untuk bertanya, terima kasih.
Program Dice Simulator Python

Program Dice Simulator Python

Program Dice Simulator Python


Pada post kali ini, saya akan membagikan program sederhana ya bisa buat nentuin giveaway, main uler tangga, main monopoli, atau sekedar nebak doang, programnya yaitu dice simulator, ya simulator dadu, langsung ke source codenya.

Source Code:

import random
print("This is a dice simulator")
x = "y"
 
while x == "y":
    number = random.randint(1,6)
 
    if number == 1:
        print("----------")
        print("|        |")
        print("|    O   |")
        print("|        |")
        print("----------")
    if number == 2:
        print("----------")
        print("|        |")
        print("| O    O |")
        print("|        |")
        print("----------")
    if number == 3:
        print("----------")
        print("|    O   |")
        print("|    O   |")
        print("|    O   |")
        print("----------")
    if number == 4:
        print("----------")
        print("| O    O |")
        print("|        |")
        print("| O    O |")
        print("----------")
    if number == 5:
        print("----------")
        print("| O    O |")
        print("|    O   |")
        print("| O    O |")
        print("----------")
    if number == 6:
        print("----------")
        print("| O    O |")
        print("| O    O |")
        print("| O    O |")
        print("----------")
    x = input("Press y to roll again ")
 
itu dia source codenya, sangat sederhana sekali, terima kasih.
Program Enkripsi Pesan Dengan Python Dalam ASCII

Program Enkripsi Pesan Dengan Python Dalam ASCII

Program Enkripsi Pesan Dengan Python Dalam ASCII


Deskripsi
Pada post kali ini saya akan membagikan atau mengshare source code program untuk enkripsi dan dekripsi suatu pesan dalam ASCII menggunakan bahasa python, program ini bisa dibilang sedikit panjang, ini juga merupakan program enkripsi dan dekripsi tingkat basic, langsung saja menuju source codenya.



Source Code

result=''
message=''
choice=''

while choice!=0:
    choice = input("\nApakah anda mau Enkripsi atau Dekripsi Pesan?\
    \nMasukkan 1 untuk Enkripsi, 2 untuk Dekripsi dan 0 untuk Keluar.\
    \nPilihan: ");

    if choice=='1':
        message=input("\nMasukkan Pesan untuk Enkripsi: ")
        for i in range(0, len(message)):
            result = result +chr(ord(message[i]) - 2)
        print(result + '\n\n')
        result = ''

    elif choice == '2':
        message = input("\nMasukkan Pesan untuk Dekripsi: ")
        for i in range(0, len(message)):
            result = result + chr(ord(message[i]) + 2)

        print(result + '\n\n')
        result=''

    elif choice !='0':
        print("Inputan Invalid!! \n\n")

itu dia source code program enkripsi dan dekripsi pesan dalam ASCII menggunakan bahasa python, jika ada pertanyaan silahkan gunakan kolom komentar yang tersedia, terima kasih.
Program Urutan Bilangan Fibonacci Dengan Python

Program Urutan Bilangan Fibonacci Dengan Python

Program Urutan Bilangan Fibonacci Dengan Python


Pada post kali ini saya akan memberikan source code program urutan bilangan fibonacci dengan menggunakan bahasa python, source code kali ini cukup singkat karena program yang lumayan sederhana, langsung saja menuju source codenya.



Source Code:

nterms = int(input("Masukkan nilai n: "))
#dua ketentuan pertama
n1 = 0
n2 = 1
count = 0
#cek apakah nomor ketentuan valid
if nterms <= 0:
    print("Mohon masukkan bilangan positif")
elif nterms == 1:
    print("Urutan Fibonacci Hingga",nterms,":")
    print(n1)
else:
    print("Urutan Fibonacci Hingga",nterms,":")
    while count < nterms:
        print(n1,end=' , ')
        nth = n1 + n2
        #perbarui nilai
        n1 = n2
        n2 = nth
        count += 1

itu dia source code program fibonacci dengan python, semoga dapat menjadi referensi anda dalam mengerjakan tugas sekolah maupun kuliah, atau sekedar menjadi referensi bagi kalian, terima kasih sudah berkunjung, jika ada yang ingin ditanyakan, silahkan gunakan kolom komentar.