2013년 7월 24일 수요일

[openCV, Python] Test Median Blur by using Salt&Pepper Noise

Median Filter : http://en.wikipedia.org/wiki/Median_filter (Wiki)

You can remove drastic noise efficiently.


import cv2
import numpy as np
import random

def MakeSaltAndPepperNoise (Image, SaltNum, PepperNum):
CopyImage = Image.copy()
nChannel = 0

# Get Image size
Width = CopyImage.shape[0]
Height = CopyImage.shape[1]

# If image is grayscale, it not have Image.shape[2]
# so it raise IndexError exception
try:
nChannel = CopyImage.shape[2]
except IndexError:
nChannel = 1

# Make Salt Noise
for Salt in range(0, SaltNum):
# Generate Random Position
RWidth = random.randrange(0, Width)
RHeight = random.randrange(0, Height)
# Make Noise
if nChannel > 1:
for c in range(0, nChannel):
CopyImage[RWidth, RHeight, c] = 255
else:
CopyImage[RWidth, RHeight] = 255

# Make Pepper Noise
for Pepper in range(0, PepperNum):
# Generate Random Position
RWidth = random.randrange(0, Width)
RHeight = random.randrange(0, Height)
# Make Noise
if nChannel > 1:
for c in range(0, nChannel):
CopyImage[RWidth, RHeight, c] = 0
else:
CopyImage[RWidth, RHeight] = 0

return CopyImage



In IDE



NoiseImage



Proccesed Image

2013년 7월 17일 수요일

[Python] Convert Integer to String

def itoa(Number, Radix=10):
    # Optional code
    if Radix > 16:
        raise ValueError("Radix bigger then 16")

    BASE = "0123456789ABCDEF"
    AlphaList = []

    while Number > 0:
        AlphaList.append(BASE[Number%Radix])
        Number /= Radix

    AlphaList.reverse()

    return "".join(AlphaList)


# in IDE

[openCV, Python] Simple trackbar code for threshold

import cv2
import numpy as np

# Callback Function for Trackbar (but do not any work)
def nothing(*arg):
    pass

# Code here
def SimpleTrackbar(Image, WindowName):
# Generate trackbar Window Name
TrackbarName = WindowName + "Trackbar"

# Make Window and Trackbar
cv2.namedWindow(WindowName)
cv2.createTrackbar(TrackbarName, WindowName, 0, 255, nothing)

# Allocate destination image
Threshold = np.zeros(Image.shape, np.uint8)

# Loop for get trackbar pos and process it
while True:
# Get position in trackbar
TrackbarPos = cv2.getTrackbarPos(TrackbarName, WindowName)
# Apply threshold
cv2.threshold(Image, TrackbarPos, 255, cv2.THRESH_BINARY, Threshold)
# Show in window
cv2.imshow(WindowName, Threshold)

# If you press "ESC", it will return value
ch = cv2.waitKey(5)
if ch == 27:
   break

 cv2.destroyAllWindows()
return Threshold


# in IDE




# Result