def validate_model(self, val_iter, epoch, step):
labels, codes, images = next(val_iter)
fake_imgs, real_imgs, d_loss, g_loss, l1_loss = self.generate_fake_samples(images, labels)
print("Sample: d_loss: %.5f, g_loss: %.5f, l1_loss: %.5f" % (d_loss, g_loss, l1_loss))
merged_fake_images = merge(scale_back(fake_imgs), [self.batch_size, 1])
merged_real_images = merge(scale_back(real_imgs), [self.batch_size, 1])
merged_pair = np.concatenate([merged_real_images, merged_fake_images], axis=1)
model_id, _ = self.get_model_id_and_dir()
model_sample_dir = os.path.join(self.sample_dir, model_id)
if not os.path.exists(model_sample_dir):
os.makedirs(model_sample_dir)
sample_img_path = os.path.join(model_sample_dir, "sample_%02d_%04d.png" % (epoch, step))
misc.imsave(sample_img_path, merged_pair)
python类imsave()的实例源码
def generate(p, ics, gcs, *args):
from scipy import misc
import subprocess
import datetime
inits = p.generate(np.array(ics),*args)
goals = p.generate(np.array(gcs),*args)
for noise_fn,output_dir in zip(noise_fns,output_dirs):
inits = noise_fn(inits)
goals = noise_fn(goals)
for i,init in enumerate(inits):
for j,goal in enumerate(goals):
d = "{}/{}/{:03d}-{:03d}-{:03d}".format(output_dir,p.__name__,steps,i,j)
try:
subprocess.call(["mv",d,d+"_old_"+datetime.datetime.today().isoformat()])
except:
pass
os.makedirs(d)
print(d)
misc.imsave(os.path.join(d,"init.png"),init)
misc.imsave(os.path.join(d,"goal.png"),goal)
################################################################
def resize_images(prms):
seqNum = range(11)
rawStr = ['rawLeftImFile', 'rawRightImFile']
imStr = ['leftImFile', 'rightImFile']
num = ku.get_num_images()
for raw, new in zip(rawStr, imStr):
for seq in seqNum:
N = num[seq]
print seq, N, raw, new
rawNames = [prms['paths'][raw] % (seq,i) for i in range(N)]
newNames = [prms['paths'][new] % (seq,i) for i in range(N)]
dirName = os.path.dirname(newNames[0])
if not os.path.exists(dirName):
os.makedirs(dirName)
for rawIm, newIm in zip(rawNames, newNames):
im = scm.imread(rawIm)
im = scm.imresize(im, [256, 256])
scm.imsave(newIm, im)
##
# Save images as jpgs.
def save_as_jpg(prms):
seqNum = range(11)
rawStr = ['rawLeftImFile', 'rawRightImFile']
imStr = ['leftImFile', 'rightImFile']
num = ku.get_num_images()
for raw, new in zip(rawStr, imStr):
for seq in seqNum:
N = num[seq]
print seq, N, raw, new
rawNames = [prms['paths'][raw] % (seq,i) for i in range(N)]
newNames = [prms['paths'][new] % (seq,i) for i in range(N)]
dirName = os.path.dirname(newNames[0])
if not os.path.exists(dirName):
os.makedirs(dirName)
for rawIm, newIm in zip(rawNames, newNames):
im = scm.imread(rawIm)
scm.imsave(newIm, im)
##
# Get the names of images
def preprocess(image_dir, new_image_dir, preprocess_fn):
image_paths = []
labels = []
if os.path.isdir(new_image_dir):
rmtree(new_image_dir)
os.makedirs(new_image_dir)
classes = os.listdir(image_dir)
for clas in classes:
class_dir = os.path.join(image_dir, str(clas))
new_class_dir = os.path.join(new_image_dir, str(clas))
os.makedirs(new_class_dir)
for image_name in os.listdir(class_dir):
image = misc.imread(os.path.join(class_dir, image_name))
image = preprocess_fn(image)
misc.imsave(os.path.join(new_class_dir, image_name), image)
def main(args):
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction = args.gpu_fraction)
with tf.Session(config=tf.ConfigProto(gpu_options = gpu_options)) as sess:
saver = tf.train.import_meta_graph('./meta_graph/my-model.meta')
saver.restore(sess,tf.train.latest_checkpoint('./model'))
image_batch = tf.get_collection('image_batch')[0]
GT_trimap = tf.get_collection('GT_trimap')[0]
pred_mattes = tf.get_collection('pred_mattes')[0]
rgb = misc.imread(args.rgb)
alpha = misc.imread(args.alpha,'L')
trimap = generate_trimap(np.expand_dims(np.copy(alpha),2),np.expand_dims(alpha,2))[:,:,0]
origin_shape = alpha.shape
rgb = np.expand_dims(misc.imresize(rgb.astype(np.uint8),[320,320,3]).astype(np.float32)-g_mean,0)
trimap = np.expand_dims(np.expand_dims(misc.imresize(trimap.astype(np.uint8),[320,320],interp = 'nearest').astype(np.float32),2),0)
feed_dict = {image_batch:rgb,GT_trimap:trimap}
pred_alpha = sess.run(pred_mattes,feed_dict = feed_dict)
final_alpha = misc.imresize(np.squeeze(pred_alpha),origin_shape)
# misc.imshow(final_alpha)
misc.imsave('./alpha.png',final_alpha)
def test_15(self):
bpth = tempfile.mkdtemp()
os.mkdir(os.path.join(bpth, 'a'))
ipth = os.path.join(bpth, 'a', 'b.png')
img = np.ones((32,32))
misc.imsave(ipth, img)
ei = util.ExampleImages(pth=bpth)
im = ei.images()
assert(len(im) > 0)
gp = ei.groups()
assert(len(gp) > 0)
img = ei.image('b.png', group='a')
assert(img.shape == (32,32))
im = ei.image('b.png', group='a', scaled=True, dtype=np.float32,
zoom=0.5)
os.remove(ipth)
os.rmdir(os.path.join(bpth, 'a'))
os.rmdir(bpth)
def save(self, data):
"""Takes in an array of CYX pixel values and writes them to a png
:param data: a CYX or YX array with C being the rgb channels for each pixel value
"""
# check for rgb, rgba, or r
if len(data.shape) == 3:
assert data.shape[0] in [4, 3, 2, 1]
# if three dimensions, transpose to YXC (imsave() needs it in these axes)
data = np.transpose(data, (1, 2, 0))
# if there's only one channel, repeat across the next two channels
if data.shape[2] == 1:
data = np.repeat(data, repeats=3, axis=2)
elif data.shape[2] == 2:
data = np.pad(data, ((0, 0), (0, 0), (0, 1)), 'constant')
elif len(data.shape) != 2:
raise ValueError("Data was not of dimensions CYX or YX")
imsave(self.file_path, data, format="png")
def test_recognize(args):
imdetect = args.detect
im1 = args.im1
im2 = args.im2
payload = {'img':file2base64(imdetect)}
import numpy as np
imarr = np.array(misc.imread(imdetect))
r = requests.get("http://face.icybee.cn/face/face_detect", data=payload)
print(json.loads(r.text)['boxes'][0])
box = json.loads(r.text)['boxes'][0]
box = [int(i) for i in box]
misc.imsave('sample.jpg',imarr[box[1]:box[3],box[0]:box[2],:],)
payload = {
'img1':file2base64(im1),
'img2':file2base64(im2)
}
r = requests.get("http://face.icybee.cn/face/face_recognize", data=payload)
print(r.text)
#print(json.loads(r.text)['dist'])
multi_augmentation_pic.py 文件源码
项目:CNN_UCMerced-LandUse_Caffe
作者: yangxue0827
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def mirror_pic(output_data_path, _dir, pic, img):
fname, fextension = os.path.splitext(pic)
mirror_x_img = img[:, ::-1, :]
mirror_x_img_gray = rgb2gray(mirror_x_img)
mirror_y_img = img[::-1, :, :]
mirror_y_img_gray = rgb2gray(mirror_y_img)
mirror_xy_img = img[::-1, ::-1, :]
mirror_xy_img_gray = rgb2gray(mirror_xy_img)
misc.imsave(os.path.join(output_data_path, _dir, (fname + '_mirror_x' + fextension)), mirror_x_img_gray)
os.chmod(os.path.join(output_data_path, _dir, (fname + '_mirror_x' + fextension)), stat.S_IWRITE)
misc.imsave(os.path.join(output_data_path, _dir, (fname + '_mirror_y' + fextension)), mirror_y_img_gray)
os.chmod(os.path.join(output_data_path, _dir, (fname + '_mirror_y' + fextension)), stat.S_IWRITE)
misc.imsave(os.path.join(output_data_path, _dir, (fname + '_mirror_xy' + fextension)), mirror_xy_img_gray)
os.chmod(os.path.join(output_data_path, _dir, (fname + '_mirror_xy' + fextension)), stat.S_IWRITE)
return mirror_x_img, mirror_y_img, mirror_xy_img
def process_mot(path):
'''
1920 x 1080 -> 384 x 216
640 x 480 -> 320 x 240
'''
images = []
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
if filename[-4:] == ".jpg" and "_ds" not in filename:
full_path = os.path.join(dirpath, filename)
img = misc.imread(full_path,mode='RGB')
if img.shape == LARGE_IMAGE_SIZE:
img = misc.imresize(img, size=LARGE_IMAGE_RESCALE)
img = pad_image(img, FINAL_IMAGE_SIZE)
elif img.shape == MEDIUM_IMAGE_SIZE:
img = misc.imresize(img, size=MEDIUM_IMAGE_RESCALE)
img = pad_image(img, FINAL_IMAGE_SIZE)
else:
print("Unexpected shape " + str(img.shape))
continue
output_filename = os.path.join(dirpath, filename[:-4] + "_ds.jpg")
misc.imsave(output_filename, img)
images.append(output_filename)
return images
def process_vot(path, min_height, min_width):
images = []
for dirpath, dirnames, filenames in os.walk(path):
img_shape = None
pad_height = 0
pad_width = 0
for filename in filenames:
if filename[-4:] == ".jpg" and "_ds" not in filename:
full_path = os.path.join(dirpath, filename)
img = misc.imread(full_path,mode='RGB')
img_shape = img.shape
ratio = min(float(min_width)/img.shape[1], float(min_height)/img.shape[0])
img = misc.imresize(img, size=ratio)
img, pad_height, pad_width = pad_image(img, (min_height, min_width))
output_filename = os.path.join(dirpath, filename[:-4] + "_ds.jpg")
misc.imsave(output_filename, img)
images.append(output_filename)
if img_shape:
gt_path = os.path.join(dirpath, "groundtruth.txt")
preprocess_label(gt_path, ratio, img_shape, min_height, min_width, pad_height, pad_width)
return images
def main():
#ids=[14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29]
ids=range(1,41)
rate=2.0/3
for id in ids:
gtfn=os.path.join(path,'P%d/V2Rct.nii.gz'%id)
# outfn=os.path.join(path,'P%d/V2Rct_all.nii.gz'%id)
gtOrg=sitk.ReadImage(gtfn)
gtMat=sitk.GetArrayFromImage(gtOrg)
print 'mat shape, ', gtMat.shape
for s in range(1,gtMat.shape[0]):
sliceMat=gtMat[s-1,:,:]
sliceMatScale = nd.interpolation.zoom(sliceMat, zoom=rate)
scmi.imsave('p%d_'%id+'s%d.png'%s, sliceMat)
#gtMat=np.transpose(gtMat,(2,1,0))
# gtVol=sitk.GetImageFromArray(gtMat)
# sitk.WriteImage(gtVol,outfn)
#
# prefn='preSub%d_as32_v12.nii'%id
# preOrg=sitk.ReadImage(prefn)
# preMat=sitk.GetArrayFromImage(preOrg)
# preMat=np.transpose(preMat,(2,1,0))
# preVol=sitk.GetImageFromArra(preMat)
# sitk.WriteImage(preVol,prefn)
def resize_to_optimal(infile, scale_ratio, rect, outfile):
image_array = imread(infile, mode='RGB')
im_shape = image_array.shape
h, w, _ = im_shape
width = float(rect.right()-rect.left())
scale_amount = (optimal_extent * scale_ratio) / width
new_w = int(scale_amount * w)
new_h = int(scale_amount * h)
new_w = new_w - (new_w % 4)
new_h = new_h - (new_h % 4)
print("optimal resize of width {} and ratio {} went from {},{} to {},{}".format(width, scale_ratio, w, h, new_w, new_h))
new_shape = (new_h, new_w)
image_array_resized = imresize(image_array, new_shape)
imsave(outfile, image_array_resized)
return new_shape
def visualize(code, filename, filename_r, filename_all):
gen.eval()
generated_by_riter = [[] for _ in range(1+opt.r_iterations)]
for i in xrange((code.size(0) - 1) // opt.batch_size + 1):
batch_size = min(opt.batch_size, code.size(0) - i * opt.batch_size)
batch_code = Variable(code[i * opt.batch_size : i * opt.batch_size + batch_size])
for r_iter in xrange(1+opt.r_iterations):
imgs, _ = gen(batch_code, n_execute_lis_layers=r_iter)
if opt.output_scale:
imgs = imgs * 2 - 1
imgs_np = (imgs.data.cpu().numpy()*255).astype(np.uint8).transpose((0, 2, 3, 1))
generated_by_riter[r_iter].extend(imgs_np)
generated_all = []
for i in xrange(len(generated_by_riter[0])):
block = [imgs[i] for imgs in generated_by_riter]
generated_all.append(np.hstack(block))
misc.imsave(filename, util.draw_grid(generated_by_riter[0], cols=opt.vis_col))
for r_iter in xrange(1, 1+opt.r_iterations):
misc.imsave(filename_r.format(r_iter-1), util.draw_grid(generated_by_riter[r_iter], cols=opt.vis_col))
misc.imsave(filename_all, util.draw_grid(generated_all, cols=opt.vis_col))
gen.train()
def generate(sample_image):
start_time = time.time()
g = ModelGraph()
with tf.Session() as sess:
# We need to initialize variables in this case because the Variable `generator/x` will not restored.
tf.sg_init(sess)
vars = [v for v in tf.global_variables() if "generator" not in v.name]
saver = tf.train.Saver(vars)
saver.restore(sess, tf.train.latest_checkpoint('asset/train/ckpt'))
i = 0
while True:
mse, _ = sess.run([g.mse, g.train_gen], {g.y: transform_image(sample_image)}) # (16, 28)
if time.time() - start_time > 60: # Save every 60 seconds
gen_image = sess.run(g.x)
gen_image = np.squeeze(gen_image)
misc.imsave('gen_images/%s/gen_%.2f.jpg' % (label, mse), gen_image)
start_time = time.time()
i += 1
if i == 60: break # Finish after 1 hour
def process_image(im_fp, dset_part):
bn = path.basename(im_fp)
dn = path.dirname(im_fp)
img_idx = int(bn[:bn.find("_")])
body_fp = path.join(dn, bn + '_body.pkl')
im = sm.imread(im_fp)
if not path.exists(body_fp):
raise Exception("Body fit not found for `%s`!" % (im_fp))
rendering = upr.render_body_impl(body_fp,
resolution=(im.shape[0], im.shape[1]),
quiet=True,
use_light=False)[0]
annotation = upm.regions_to_classes(rendering, upm.six_region_groups,
warn_id=str(img_idx))
out_fp = path.join('..', 'data', 'pose', 'extracted', dset_part,
"{:0{width}d}_bodysegments.png".format(
img_idx, width=bn.find("_")))
sm.imsave(out_fp, annotation)
out_fp = path.join('..', 'data', 'pose', 'extracted', dset_part,
"{:0{width}d}_bodysegments_vis.png".format(
img_idx, width=bn.find("_")))
sm.imsave(out_fp, vs.apply_colormap(annotation, vmin=0, vmax=6,
cmap=config.CMAP)[:, :, 0:3])
def process_frame(frame_idx, img, model, write_to_dir, conf_threshold, input_size=224):
"""Finds bounding boxes in a video frame, draws these bounding boxes
and saves the result to HDD.
"""
# find BBs in frame
bbs, time_model = find_bbs(img, model, conf_threshold, input_size=input_size)
# draw BBs
img_out = np.copy(img)
for (bb, score) in bbs:
if score > conf_threshold and bb.width > 2 and bb.height > 2:
img_out = bb.draw_on_image(img_out, color=[0, 255, 0], thickness=3)
# save to output directory
save_to_fp = os.path.join(write_to_dir, "%05d.jpg" % (frame_idx,))
misc.imsave(save_to_fp, img_out)
return time_model
def main():
img = imread(args.input_path)
img = ndimage.rotate(img, args.angle, mode=args.mode)
misc.imsave(args.output_path, img)
def main():
print(args)
for dir_path, dir_names, file_names in os.walk(args.input_data_dir):
# dir_path is a string, the path to the directory
# dir_names is a list of the names of the subdirectories in dir_path (excluding '.' and '..')
# file_names is a list of the names of the non-directory files in dir_path
dir_absolute_path = args.output_data_dir + dir_path.replace(args.input_data_dir, '')
if not os.path.exists(dir_absolute_path):
os.mkdir(dir_absolute_path)
for file_name in file_names:
# Split the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins
# with a period and contains at most one period.
(root, ext) = os.path.splitext(file_name)
new_file_name = '%s/%s.%dx%d%s' % (
dir_absolute_path, root, args.width, args.height, ext)
print(new_file_name)
if not os.path.exists(new_file_name):
img = imread(dir_path + '/' + file_name)
# type(img) = ndarray, https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html
(width, height) = img.shape[0:2]
if width > height:
size = (args.width, height * args.width / width)
else:
size = (width * args.height / height, args.height)
new_img = misc.imresize(img, size)
misc.imsave(new_file_name, new_img)
def setup(self, pre_encode=False):
sbd_path = get_data_path('sbd')
voc_path = get_data_path('pascal')
target_path = self.root + '/SegmentationClass/pre_encoded/'
if not os.path.exists(target_path):
os.makedirs(target_path)
sbd_train_list = tuple(open(sbd_path + 'dataset/train.txt', 'r'))
sbd_train_list = [id_.rstrip() for id_ in sbd_train_list]
self.files['train_aug'] = self.files['train'] + sbd_train_list
if pre_encode:
print("Pre-encoding segmentation masks...")
for i in tqdm(sbd_train_list):
lbl_path = sbd_path + 'dataset/cls/' + i + '.mat'
lbl = io.loadmat(lbl_path)['GTcls'][0]['Segmentation'][0].astype(np.int32)
lbl = m.toimage(lbl, high=lbl.max(), low=lbl.min())
m.imsave(target_path + i + '.png', lbl)
for i in tqdm(self.files['trainval']):
lbl_path = self.root + '/SegmentationClass/' + i + '.png'
lbl = self.encode_segmap(m.imread(lbl_path))
lbl = m.toimage(lbl, high=lbl.max(), low=lbl.min())
m.imsave(target_path + i + '.png', lbl)
def pcaCreate(image_files,dir,name_num, dir_list):
image_list = []
new_file_name = dir
save_dir = dir_list + new_file_name
save_dir_tt = save_dir + "\\"
for image_file in image_files:
image_list.append(misc.imread(image_file))
for image in image_list:
img = np.asarray(image, dtype='float32')
img = img / 255.
img_size = img.size / 3
img1 = img.reshape(img_size, 3)
img1 = np.transpose(img1)
img_cov = np.cov([img1[0], img1[1], img1[2]])
lamda, p = np.linalg.eig(img_cov)
p = np.transpose(p)
alpha1 = random.normalvariate(0, 0.3)
alpha2 = random.normalvariate(0, 0.3)
alpha3 = random.normalvariate(0, 0.3)
v = np.transpose((alpha1 * lamda[0], alpha2 * lamda[1], alpha3 * lamda[2]))
add_num = np.dot(p, v)
img2 = np.array([img[:, :, 0] + add_num[0], img[:, :, 1] + add_num[1], img[:, :, 2] + add_num[2]])
img2 = np.swapaxes(img2, 0, 2)
img2 = np.swapaxes(img2, 0, 1)
misc.imsave(save_dir_tt + np.str(name_num) + '.jpg', img2)
name_num += 1
return image_list
def pcaCreate_Ori(image_files,dir):
parser = argparse.ArgumentParser()
parser.add_argument("file_suffix", help="specific the file suffix")
parser.add_argument("root_dir", help="E:\\")
parser.add_argument("-f", "--file", help="record result to file")
parser.add_argument("data_set",help= "specific the file suffix")
args = parser.parse_args()
img_num = len(os.listdir(args.root_dir + '/' + args.dataset))
for i in range(img_num):
img_name = os.listdir(args.root_dir + '/' + args.dataset)[i]
img = Image.open(os.path.join(args.root_dir, args.dataset, img_name))
img = np.asarray(img, dtype='float32')
img = img / 255.
img_size = img.size / 3
img1 = img.reshape(img_size, 3)
img1 = np.transpose(img1)
img_cov = np.cov([img1[0], img1[1], img1[2]])
lamda, p = np.linalg.eig(img_cov)
p = np.transpose(p)
alpha1 = random.normalvariate(0, 0.3)
alpha2 = random.normalvariate(0, 0.3)
alpha3 = random.normalvariate(0, 0.3)
v = np.transpose((alpha1 * lamda[0], alpha2 * lamda[1], alpha3 * lamda[2]))
add_num = np.dot(p, v)
img2 = np.array([img[:, :, 0] + add_num[0], img[:, :, 1] + add_num[1], img[:, :, 2] + add_num[2]])
img2 = np.swapaxes(img2, 0, 2)
img2 = np.swapaxes(img2, 0, 1)
misc.imsave('test2222.jpg', img2)
def saveImage(rgb_array, savepath):
"""
Converts image array to file
:param rgb_array: input rgb array
:param savepath: save file location
"""
misc.imsave(savepath, rgb_array)
def saveAllImages(rgb_array, directory, foldername):
"""
Saves unfiltered and filtered images to a file directory
:param rgb_array: image rgb array
:param directory: image directory name
:param foldername: name of the folder that will contain saved files
:return:
"""
rgb_array_red = rgb_array * 1
r_array = setImageColor(rgb_array_red, 'r')
rgb_array_green = rgb_array * 1
g_array = setImageColor(rgb_array_green, 'g')
rgb_array_blue = rgb_array * 1
b_array = setImageColor(rgb_array_blue, 'b')
trueimage = 'image.png'
redimage = 'red.png'
greenimage = 'green.png'
blueimage = 'blue.png'
plotimage = 'plot.png'
if not os.path.exists(os.path.join(directory, foldername)):
os.mkdir(os.path.join(directory, foldername))
misc.imsave(os.path.join(directory, foldername, trueimage), rgb_array)
misc.imsave(os.path.join(directory, foldername, redimage), r_array)
misc.imsave(os.path.join(directory, foldername, greenimage), g_array)
misc.imsave(os.path.join(directory, foldername, blueimage), b_array)
savePlot(rgb_array, os.path.join(directory, foldername, plotimage))
def main():
'''
????????
'''
im_array = ndimage.imread("greytech.png", mode='RGB')
print(len(im_array), len(im_array[0]))
color = set()
for i in im_array:
for j in i:
color.add(tuple(j))
# tmp = [[0 for i in range(len(im_array[0]))] for j in range(len(im_array))]
#
# for i in range((len(im_array))):
# for j in range(len(im_array[0])):
# print(str(tuple(im_array[i][j])))
# if str(tuple(im_array[i][j]))!= "(255, 255, 255)":
# tmp[i][j]=(0,0,0)
# else:
# tmp[i][j]=im_array[i][j]
#
# misc.imsave("test.bmp", tmp)
print('{')
for i in color:
print("\"{0}\":,".format(i))
print('}')
# for noi,i in enumerate(im_array):
# for noj,j in enumerate(i):
# print("Row:%d Col:%d color: %s" %(noi, noj, j))
def main():
'''
????????
'''
im_array = ndimage.imread("ustc.bmp", mode='RGB')
print(len(im_array), len(im_array))
color = set()
for i in im_array:
for j in i:
color.add(tuple(j))
# tmp = [[0 for i in range(len(im_array[0]))] for j in range(len(im_array))]
#
# for i in range((len(im_array))):
# for j in range(len(im_array[0])):
# print(str(tuple(im_array[i][j])))
# if str(tuple(im_array[i][j]))!= "(255, 255, 255)":
# tmp[i][j]=(0,0,0)
# else:
# tmp[i][j]=im_array[i][j]
#
# misc.imsave("test.bmp", tmp)
print('{')
for i in color:
print("\"{0}\":,".format(i))
print('}')
# for noi,i in enumerate(im_array):
# for noj,j in enumerate(i):
# print("Row:%d Col:%d color: %s" %(noi, noj, j))
def main():
'''
????????
'''
im_array = ndimage.imread("greytech.png", mode='RGB')
print(len(im_array), len(im_array[0]))
color = set()
for i in im_array:
for j in i:
color.add(tuple(j))
# tmp = [[0 for i in range(len(im_array[0]))] for j in range(len(im_array))]
#
# for i in range((len(im_array))):
# for j in range(len(im_array[0])):
# print(str(tuple(im_array[i][j])))
# if str(tuple(im_array[i][j]))!= "(255, 255, 255)":
# tmp[i][j]=(0,0,0)
# else:
# tmp[i][j]=im_array[i][j]
#
# misc.imsave("test.bmp", tmp)
print('{')
for i in color:
print("\"{0}\":,".format(i))
print('}')
# for noi,i in enumerate(im_array):
# for noj,j in enumerate(i):
# print("Row:%d Col:%d color: %s" %(noi, noj, j))
def main():
'''
????????
'''
im_array = ndimage.imread("ms.bmp", mode='RGB')
print(len(im_array), len(im_array))
color = set()
for i in im_array:
for j in i:
color.add(tuple(j))
# tmp = [[0 for i in range(len(im_array[0]))] for j in range(len(im_array))]
#
# for i in range((len(im_array))):
# for j in range(len(im_array[0])):
# print(str(tuple(im_array[i][j])))
# if str(tuple(im_array[i][j]))!= "(255, 255, 255)":
# tmp[i][j]=(0,0,0)
# else:
# tmp[i][j]=im_array[i][j]
#
# misc.imsave("test.bmp", tmp)
print('{')
for i in color:
print("\"{0}\":,".format(i))
print('}')
# for noi,i in enumerate(im_array):
# for noj,j in enumerate(i):
# print("Row:%d Col:%d color: %s" %(noi, noj, j))
def main():
'''
????????
'''
im_array = ndimage.imread("greytech.png", mode='RGB')
print(len(im_array), len(im_array[0]))
color = set()
for i in im_array:
for j in i:
color.add(tuple(j))
# tmp = [[0 for i in range(len(im_array[0]))] for j in range(len(im_array))]
#
# for i in range((len(im_array))):
# for j in range(len(im_array[0])):
# print(str(tuple(im_array[i][j])))
# if str(tuple(im_array[i][j]))!= "(255, 255, 255)":
# tmp[i][j]=(0,0,0)
# else:
# tmp[i][j]=im_array[i][j]
#
# misc.imsave("test.bmp", tmp)
print('{')
for i in color:
print("\"{0}\":,".format(i))
print('}')
# for noi,i in enumerate(im_array):
# for noj,j in enumerate(i):
# print("Row:%d Col:%d color: %s" %(noi, noj, j))