def color_swap(src):
img_bgr = cv2.split(src)
dst = cv2.merge((img_bgr[2], img_bgr[1], img_bgr[0])) # from BGR to RGB
return dst
python类merge()的实例源码
def color_sepia(src):
img_bgr = cv2.split(src)
# R=A, G=0.8xA, B=0.55xA
dst = cv2.merge((img_bgr[0] * 0.55 , img_bgr[1] * 0.8, img_bgr[2] * 1.0))
return dst
def image_preprocess(img):
b, g, r = cv2.split(img)
return cv2.merge([(b-mean_value[0])/std[0], (g-mean_value[1])/std[1], (r-mean_value[2])/std[2]])
def yuvPassShadowRemoval(src, shadowThreshold):
height, width = src.shape[:2]
imgYUV = cv2.cvtColor(src, cv2.COLOR_RGB2YUV)
yImg, uImg, vImg = cv2.split(imgYUV)
# for i in range(0, height):
# for j in range(0, width):
# yImg[i, j] = 0
yImg = np.zeros((height, width, 1), np.uint8)
imgYUV = cv2.merge([yImg, uImg, vImg])
rgbImg = cv2.cvtColor(imgYUV, cv2.COLOR_YUV2RGB)
rImg, gImg, bImg = cv2.split(rgbImg)
count = width * height
avg = np.sum(bImg)
avg /= count * 1.0
# for i in range(0, height):
# for j in range(0, width):
# if bImg[i, j] > ave:
# rImg[i, j] = 255
# gImg[i, j] = 255
# bImg[i, j] = 255
# else:
# rImg[i, j] = 0
# gImg[i, j] = 0
# bImg[i, j] = 0
if shadowThreshold is None:
avg = avg
else:
avg = shadowThreshold
np.where(bImg > avg, 255, 0)
_, threshold = cv2.threshold(bImg, avg, 255, cv2.THRESH_BINARY)
output = threshold
return output
def rgb(bgr_img):
b,g,r = cv.split(bgr_img) # get b,g,r
rgb_img = cv.merge([r,g,b]) # switch it to rgb
return rgb_img
# Given directory loc, get all images in directory and crop to just faces
# Returns face_list, an array of cropped image file names
def toggleRGB(img):
r,g,b = cv.split(img)
img = cv.merge([b,g,r])
return img
# Combine two images for displaying side-by-side
# If maxSize is true, crops sides of image to keep under 2880 pixel width of screen
def load_minibatch(input_list, color, labels, start,num):
# Enforce minimum on start
start = max(0,start)
# Enforce maximum on end
end = start + num
end = min(len(input_list), end)
# Isolate files
files = input_list[start:end]
images = []
for file in files:
img = caffe.io.load_image(file, color)
# Handle incorrect image dims for uncropped images
# TODO: Get uncropped images to import correctly
if img.shape[0] == 3 or img.shape[0] == 1:
img = np.swapaxes(np.swapaxes(img, 0, 1), 1, 2)
# BUG FIX: Is this ok?
# color=True gets the correct desired dimension of WxHx3
# But color=False gets images of WxHx1. Need WxHx3 or will get "Index out of bounds" exception
# Fix by concatenating three copies of the image
if img.shape[2] == 1:
img = cv.merge([img,img,img])
# Add image array to batch
images.append(img)
labelsReduced = labels[start:end]
return images, labelsReduced
# Big function:
# Classify all images in a list of image file names
# Using the inputs, constructs a network, imports images either individually or in minibatches,
# gets the network classification, and builds up the confusion matrix.
# No return value, but it can plot the confusion matrix at the end
def ImageWrite(image, name, step):
r,g,b = cv2.split(image)
image = cv2.merge([b,g,r])
filename = 'styleA_%s_styleB_%s_' % (FLAGS.style_A, FLAGS.style_B)
filename += name
filename += '_%06.d.jpg' % step
cv2.imwrite(filename, image)
def read_images(filenames, domain=None, image_size=64):
images = []
for fn in filenames:
image = cv2.imread(fn)
if image is None:
continue
if domain == 'A':
kernel = np.ones((3,3), np.uint8)
image = image[:, :256, :]
image = 255. - image
image = cv2.dilate( image, kernel, iterations=1 )
image = 255. - image
elif domain == 'B':
image = image[:, 256:, :]
image = cv2.resize(image, (image_size,image_size))
# Change the order of channels
r,g,b = cv2.split(image)
image = cv2.merge([b,g,r])
# Scale from [0, 255] to [-1, 1]
image = image.astype(np.float32) / 255.
image -= 0.5
image *= 2.0
# TensorFlow shape (height, width, channels)
#image = image.transpose(2,0,1)
images.append( image )
images = np.stack( images )
return images
def apply_median(k):
''' Apply the given kernel to images
This function searches through the images/source subfolder, and
uses your convolution funciton implemented in part0 to apply the given kernel
to each image found inside. It will then save the resulting images to the
images/filtered subfolder, appending their names with kernel_name.
'''
print 'applying median filter to images'
sourcefolder = os.path.abspath(os.path.join(os.curdir, 'images', 'source'))
outfolder = os.path.abspath(os.path.join(os.curdir, 'images', 'filtered'))
print 'Searching for images in {} folder'.format(sourcefolder)
exts = ['.bmp', '.pbm', '.pgm', '.ppm', '.sr', '.ras', '.jpeg', '.jpg',
'.jpe', '.jp2', '.tiff', '.tif', '.png']
for dirname, dirnames, filenames in os.walk(sourcefolder):
for filename in filenames:
name, ext = os.path.splitext(filename)
if ext in exts:
print "Reading image {}.".format(filename)
img = cv2.imread(os.path.join(dirname, filename))
print "Applying filter."
if len(img.shape) == 2:
outimg = part3.filter_median(img, k)
else:
outimg = []
for channel in range(img.shape[2]):
outimg.append(part3.filter_median(img[:,:,channel], k))
outimg = cv2.merge(outimg)
outpath = os.path.join(outfolder, name + 'median' + str(k) + ext)
print "Writing image {}.\n\n".format(outpath)
cv2.imwrite(outpath, outimg)
def apply_filter(conv_func, kernel, kernel_name):
''' Apply the given kernel to images
This function searches through the images/source subfolder, and
uses your convolution funciton implemented in part0 to apply the given kernel
to each image found inside. It will then save the resulting images to the
images/filtered subfolder, appending their names with kernel_name.
'''
print 'applying {} kernel to images'.format(kernel_name)
sourcefolder = os.path.abspath(os.path.join(os.curdir, 'images', 'source'))
outfolder = os.path.abspath(os.path.join(os.curdir, 'images', 'filtered'))
print 'Searching for images in {} folder'.format(sourcefolder)
exts = ['.bmp', '.pbm', '.pgm', '.ppm', '.sr', '.ras', '.jpeg', '.jpg',
'.jpe', '.jp2', '.tiff', '.tif', '.png']
for dirname, dirnames, filenames in os.walk(sourcefolder):
for filename in filenames:
name, ext = os.path.splitext(filename)
if ext in exts:
print "Reading image {}.".format(filename)
img = cv2.imread(os.path.join(dirname, filename))
print "Applying filter."
if len(img.shape) == 2:
outimg = conv_func(img, kernel)
else:
outimg = []
for channel in range(img.shape[2]):
outimg.append(conv_func(img[:,:,channel], kernel))
outimg = cv2.merge(outimg)
outpath = os.path.join(outfolder, name + kernel_name + ext)
print "Writing image {}.\n\n".format(outpath)
cv2.imwrite(outpath, outimg)
def equalize_hist_all(self, root='../data/val/'):
raw_root, out_root = root + 'images/', root + 'normalized/'
if not os.path.exists(out_root):
os.mkdir(out_root)
cnt = 0
for parent, _, files in os.walk(raw_root):
for name in files:
img = cv2.imread(parent + name)
b, g, r = cv2.split(img)
bb, gg, rr = cv2.equalizeHist(b), cv2.equalizeHist(g), cv2.equalizeHist(r)
[row, col] = b.shape
if row > col:
d = row - col
add_block = np.zeros((d, row))
new_bb = np.vstack((bb.T, add_block))
new_gg = np.vstack((gg.T, add_block))
new_rr = np.vstack((rr.T, add_block))
new_bb = new_bb.T
new_gg = new_gg.T
new_rr = new_rr.T
else:
d = col - row
add_block = np.zeros((d, col))
new_bb = np.vstack((add_block, bb))
new_gg = np.vstack((add_block, gg))
new_rr = np.vstack((add_block, rr))
new_bb, new_gg, new_rr = np.uint8(new_bb), np.uint8(new_gg), np.uint8(new_rr)
new_image = cv2.merge([new_bb, new_gg, new_rr])
res = cv2.resize(new_image, (100, 100), interpolation=cv2.INTER_CUBIC)
new_name = out_root + name
cv2.imwrite(new_name, res)
cnt += 1
if cnt % 500 == 0:
print 'Processed', cnt, 'images!'
def hisEqulColor(img):
ycrcb=cv2.cvtColor(img,cv2.COLOR_BGR2YCR_CB)
channels=cv2.split(ycrcb)
# create a CLAHE object
clahe = cv2.createCLAHE()
channels[0] = clahe.apply(channels[0])
cv2.merge(channels,ycrcb)
cv2.cvtColor(ycrcb,cv2.COLOR_YCR_CB2BGR,img)
def get_rescaled(fname, rescaled_directory):
rescaled_fname = fname + ".rescaled.png"
rescaled = os.path.join(rescaled_directory, rescaled_fname)
image = cv2.imread(rescaled, cv2.IMREAD_UNCHANGED)
if image is None:
print "Failed to read image from", rescaled
return i, None
# hisEqulColor(image)
b_channel, g_channel, r_channel = cv2.split(image)
alpha_channel = np.ones(b_channel.shape, dtype=b_channel.dtype) * 255
image = cv2.merge((b_channel, g_channel, r_channel, alpha_channel))
return image
def mergeBGR(B, G, R):
try:
mergedBGR = cv2.merge((B, G, R))
except TypeError:
B = load_image(B, mode=0)
G = load_image(G, mode=0)
R = load_image(R, mode=0)
mergedBGR = cv2.merge((B, G, R))
# cv2.imshow('bgr', mergedBGR)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
return mergedBGR
def mergeHSV(H, S, V):
try:
mergedHSV = cv2.merge((H, S, V))
except TypeError:
H = load_image(H, mode=0)
S = load_image(S, mode=0)
V = load_image(V, mode=0)
mergedHSV = cv2.merge((H, S, V))
HSV2RGB = cv2.cvtColor(mergedHSV, cv2.COLOR_HSV2BGR)
# cv2.imshow('hsv', HSV2RGB)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
return HSV2RGB
def simplest_cb(img, percent):
assert img.shape[2] == 3
assert percent > 0 and percent < 100
half_percent = percent / 200.0
channels = cv2.split(img)
out_channels = []
for channel in channels:
assert len(channel.shape) == 2
# find the low and high precentile values (based on the input percentile)
height, width = channel.shape
vec_size = width * height
flat = channel.reshape(vec_size)
assert len(flat.shape) == 1
flat = np.sort(flat)
n_cols = flat.shape[0]
low_val = flat[math.floor(n_cols * half_percent)]
high_val = flat[math.ceil( n_cols * (1.0 - half_percent))]
print "Lowval: ", low_val
print "Highval: ", high_val
# saturate below the low percentile and above the high percentile
thresholded = apply_threshold(channel, low_val, high_val)
# scale the channel
normalized = cv2.normalize(thresholded, thresholded.copy(), 0, 255, cv2.NORM_MINMAX)
out_channels.append(normalized)
return cv2.merge(out_channels)
def equalize_BGR_image(image):
""" Histogram eq whole color image."""
b, g, r = cv.split(image)
b = equalize_image_channel(b)
g = equalize_image_channel(g)
r = equalize_image_channel(r)
return cv.merge((b,g,r))
def equalize_BGR_image_adaptive(image):
""" Adaptive color image equalization (CLAHE)."""
b, g, r = cv.split(image)
b = equalize_image_channel_adaptive(b)
g = equalize_image_channel_adaptive(g)
r = equalize_image_channel_adaptive(r)
return cv.merge((b,g,r))
def change_light(image, value, channel="v"):
""" Change the light intensity of an image."""
channelDic = {"h": 0, "s":1, "v":2}
# "translate" image channel to channel index
if not channel in channelDic:
raise AttributeError("invalid channel value. Valid values are h, s, or v")
# which format (ConvNet (3, w, h) vs. Normal (w, h, 3)
reshape = False
prevShape = image.shape
if image.shape[0] == 3 or image.shape[0] == 1:
reshape = True
if image.shape[0] == image.shape[1] or (image.shape[0] == 1 and image.shape[1] == 3): # grayscale 1L, 1L, h, w OR color 1L, 3L, h, w
reshapeVector = (image.shape[2], image.shape[3], image.shape[1])
else:
reshapeVector = (image.shape[1], image.shape[2], image.shape[0]) # single row color or grayscale 1L/3L, h, w
image = image.reshape(reshapeVector)
#print "Shape",image.shape
#print "dtype",image.dtype
# convert to hsv
hsv = cv.cvtColor(image, cv.COLOR_BGR2HSV)
# hsv[:,:,2] += value - would be way faster but this does not prevent overflow (a high value gets even higher and becomes 0)
channels = cv.split(hsv)
for row in xrange(len(channels[channelDic[channel]])):
for col in xrange(len(channels[channelDic[channel]][0])):
channels[channelDic[channel]][row][col] = max(min(255, channels[channelDic[channel]][row][col]*value),0)
image = cv.cvtColor(cv.merge(channels), cv.COLOR_HSV2BGR)
# reshape back
if reshape:
image = image.reshape(prevShape)
return image