def readimage():
image = cv2.imread('test.jpg', cv2.IMREAD_GRAYSCALE) # reading image
if image is None:
print 'Can not find the image!'
exit(-1)
return image
#-------------------------------------------------------------------------------------
python类IMREAD_GRAYSCALE的实例源码
def readimage(filename):
print filename
image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) # reading image
if image is None:
print 'Can not find the image!'
sys.stdin.read(1)
exit(-1)
return image
#-------------------------------------------------------------------------------------
def readimage(filename):
print filename
image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) # reading image
if image is None:
print 'Can not find the image!'
sys.stdin.read(1)
exit(-1)
return image
#-------------------------------------------------------------------------------------
def test_swt(self):
cv2.IMREAD_GRAYSCALE
image = cv2.imread(os.path.join(self.photodir,"GloryDays","bib-sample.jpg"),cv2.IMREAD_GRAYSCALE)
SWTImage = SWTScrubber.scrub(image)
cv2.imwrite(os.path.join(self.photooutdir,"SWTImage.jpg"),SWTImage*255)
def test_find_scene():
scenes = {}
for s in os.listdir('txxscene'):
if '-' in s: continue
i = cv2.imread(os.path.join('txxscene', s), cv2.IMREAD_GRAYSCALE)
scenes[s] = i
# names = [os.path.join('scene', c) for c in os.listdir('scene')]
imgs = {}
for n in os.listdir('scene'):
i = cv2.imread(os.path.join('scene', n), cv2.IMREAD_GRAYSCALE)
i = cv2.resize(i, (960, 540))
imgs[n] = i
for name, img in imgs.iteritems():
for scene, tmpl in scenes.iteritems():
res = cv2.matchTemplate(img, tmpl, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
if max_val < 0.6:
continue
x, y = max_loc
h, w = tmpl.shape
cv2.rectangle(img, (x, y), (x+w, y+h), 255, 2)
print name, scene, max_val, min_val
cv2.imshow('found', img)
cv2.waitKey()
def test_find_scene():
scenes = {}
for s in os.listdir('txxscene'):
if '-' in s: continue
i = cv2.imread(os.path.join('txxscene', s), cv2.IMREAD_GRAYSCALE)
scenes[s] = i
# names = [os.path.join('scene', c) for c in os.listdir('scene')]
imgs = {}
for n in os.listdir('scene'):
i = cv2.imread(os.path.join('scene', n), cv2.IMREAD_GRAYSCALE)
i = cv2.resize(i, (960, 540))
imgs[n] = i
for name, img in imgs.iteritems():
for scene, tmpl in scenes.iteritems():
res = cv2.matchTemplate(img, tmpl, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
if max_val < 0.6:
continue
x, y = max_loc
h, w = tmpl.shape
cv2.rectangle(img, (x, y), (x+w, y+h), 255, 2)
print name, scene, max_val, min_val
cv2.imshow('found', img)
cv2.waitKey()
def print_image(url):
global mutex
img_file = requests.get(url)
image = np.asarray(bytearray(img_file.content), dtype='uint8')
im = cv2.imdecode(image, cv2.IMREAD_GRAYSCALE)
pixels = ImageConverter.im2bmp(im)
mutex.acquire()
try:
mmj = BtManager("69:68:63:69:61:68")
if mmj.connected:
stop = int(time.time()) + len(pixels) / 384 / 5
mmj.sendImageToBt(pixels)
mmj.disconnect()
time_to_sleep = stop - int(time.time())
time.sleep(time_to_sleep if time_to_sleep > 0 else 0)
finally:
mutex.release()
def create_train_data():
"""
Generate training data numpy arrays and save them into the project path
"""
image_rows = 420
image_cols = 580
images = os.listdir(data_path)
masks = os.listdir(masks_path)
total = len(images)
imgs = np.ndarray((total, 1, image_rows, image_cols), dtype=np.uint8)
imgs_mask = np.ndarray((total, 1, image_rows, image_cols), dtype=np.uint8)
for image_name in images:
img = cv2.imread(os.path.join(data_path, image_name), cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (image_rows, image_cols), interpolation=cv2.INTER_CUBIC)
img = np.array([img])
imgs[i] = img
for image_mask_name in masks:
img_mask = cv2.imread(os.path.join(masks_path, image_mask_name), cv2.IMREAD_GRAYSCALE)
img_mask = cv2.resize(img_mask, (image_rows, image_cols), interpolation=cv2.INTER_CUBIC)
img_mask = np.array([img_mask])
imgs_mask[i] = img_mask
np.save('imgs_train.npy', imgs)
np.save('imgs_mask_train.npy', imgs_mask)
def load_image(filename):
"""Reads an image from file. Image is being converted to grayscale and resized."""
image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
if image is None:
raise ImageLoaderError(filename)
return convert_image(image)
def load_image_from_buf(buf):
"""Reads an image from a buffer in memory. Image is being converted to grayscale and resized."""
if len(buf) == 0:
raise ImageLoaderError()
image = cv2.imdecode(numpy.frombuffer(buf, numpy.uint8), cv2.IMREAD_GRAYSCALE)
if image is None:
raise ImageLoaderError()
return convert_image(image)
def _openImage(filename):
return cv2.imread(filename,
# cv2.IMREAD_ANYDEPTH |
cv2.IMREAD_GRAYSCALE)
def imread(img, color=None, dtype=None):
'''
dtype = 'noUint', uint8, float, 'float', ...
'''
COLOR2CV = {'gray': cv2.IMREAD_GRAYSCALE,
'all': cv2.IMREAD_COLOR,
None: cv2.IMREAD_ANYCOLOR
}
c = COLOR2CV[color]
if callable(img):
img = img()
elif isinstance(img, string_types):
# from_file = True
# try:
# ftype = img[img.find('.'):]
# img = READERS[ftype](img)[0]
# except KeyError:
# open with openCV
# grey - 8 bit
if dtype in (None, "noUint") or np.dtype(dtype) != np.uint8:
c |= cv2.IMREAD_ANYDEPTH
img2 = cv2.imread(img, c)
if img2 is None:
raise IOError("image '%s' is not existing" % img)
img = img2
elif color == 'gray' and img.ndim == 3: # multi channel img like rgb
# cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #cannot handle float64
img = toGray(img)
# transform array to uint8 array due to openCV restriction
if dtype is not None:
if isinstance(img, np.ndarray):
img = _changeArrayDType(img, dtype, cutHigh=False)
return img
def open(self, filename):
p = self.preferences
# open in 8 bit?
if p.p8bit.value():
col = 0
else:
col = cv2.IMREAD_ANYDEPTH
if p.pGrey.value() and not p.pSplitColors.value():
col = col | cv2.IMREAD_GRAYSCALE
else:
col |= cv2.IMREAD_ANYCOLOR
# OPEN
img = cv2.imread(str(filename), col) # cv2.IMREAD_UNCHANGED)
if img is None:
raise Exception("image '%s' doesn't exist" % filename)
# crop
if p.pCrop.value():
r = (p.pCropX0.value(),
p.pCropX1.value(),
p.pCropY0.value(),
p.pCropY1.value())
img = img[r[0]:r[1], r[2]:r[3]]
# resize
if p.pResize.value():
img = cv2.resize(img, (p.pResizeX.value(), p.pResizeY.value()))
labels = None
if img.ndim == 3:
if p.pSplitColors.value():
img = np.transpose(img, axes=(2, 0, 1))
labels = ['blue', 'green', 'red']
else:
# rgb convention
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# change data type to float
img = self.toFloat(img)
return img, labels
def __getitem__(self, index):
datafiles = self.files[index]
image = cv2.imread(datafiles["img"], cv2.IMREAD_COLOR)
label = cv2.imread(datafiles["label"], cv2.IMREAD_GRAYSCALE)
size = image.shape
name = datafiles["name"]
if self.scale:
image, label = self.generate_scale_label(image, label)
image = np.asarray(image, np.float32)
image -= self.mean
img_h, img_w = label.shape
pad_h = max(self.crop_h - img_h, 0)
pad_w = max(self.crop_w - img_w, 0)
if pad_h > 0 or pad_w > 0:
img_pad = cv2.copyMakeBorder(image, 0, pad_h, 0,
pad_w, cv2.BORDER_CONSTANT,
value=(0.0, 0.0, 0.0))
label_pad = cv2.copyMakeBorder(label, 0, pad_h, 0,
pad_w, cv2.BORDER_CONSTANT,
value=(self.ignore_label,))
else:
img_pad, label_pad = image, label
img_h, img_w = label_pad.shape
h_off = random.randint(0, img_h - self.crop_h)
w_off = random.randint(0, img_w - self.crop_w)
# roi = cv2.Rect(w_off, h_off, self.crop_w, self.crop_h);
image = np.asarray(img_pad[h_off : h_off+self.crop_h, w_off : w_off+self.crop_w], np.float32)
label = np.asarray(label_pad[h_off : h_off+self.crop_h, w_off : w_off+self.crop_w], np.float32)
#image = image[:, :, ::-1] # change to BGR
image = image.transpose((2, 0, 1))
if self.is_mirror:
flip = np.random.choice(2) * 2 - 1
image = image[:, :, ::flip]
label = label[:, ::flip]
return image.copy(), label.copy(), np.array(size), name
def __getitem__(self, index):
datafiles = self.files[index]
image = cv2.imread(datafiles["img"], cv2.IMREAD_COLOR)
label = cv2.imread(datafiles["label"], cv2.IMREAD_GRAYSCALE)
size = image.shape
name = datafiles["name"]
if self.scale:
image, label = self.generate_scale_label(image, label)
image = np.asarray(image, np.float32)
image -= self.mean
img_h, img_w = label.shape
pad_h = max(self.crop_h - img_h, 0)
pad_w = max(self.crop_w - img_w, 0)
if pad_h > 0 or pad_w > 0:
img_pad = cv2.copyMakeBorder(image, 0, pad_h, 0,
pad_w, cv2.BORDER_CONSTANT,
value=(0.0, 0.0, 0.0))
label_pad = cv2.copyMakeBorder(label, 0, pad_h, 0,
pad_w, cv2.BORDER_CONSTANT,
value=(self.ignore_label,))
else:
img_pad, label_pad = image, label
img_h, img_w = label_pad.shape
h_off = random.randint(0, img_h - self.crop_h)
w_off = random.randint(0, img_w - self.crop_w)
# roi = cv2.Rect(w_off, h_off, self.crop_w, self.crop_h);
image = np.asarray(img_pad[h_off : h_off+self.crop_h, w_off : w_off+self.crop_w], np.float32)
label = np.asarray(label_pad[h_off : h_off+self.crop_h, w_off : w_off+self.crop_w], np.float32)
#image = image[:, :, ::-1] # change to BGR
image = image.transpose((2, 0, 1))
if self.is_mirror:
flip = np.random.choice(2) * 2 - 1
image = image[:, :, ::flip]
label = label[:, ::flip]
return image.copy(), label.copy(), np.array(size), name
def get_figs(dir_name):
ret = []
for file_name in os.listdir(dir_name):
#tmp = cv2.imread(os.path.join(dir_name, file_name), cv2.IMREAD_GRAYSCALE)
#tmp = np.reshape(tmp, (64, 64, 1))
tmp = cv2.imread(os.path.join(dir_name, file_name))
ret.append(tmp/127.5 - 1.0)
return np.asarray(ret, dtype = np.float32)
def _deal_image_(self):
img = cv2.imread(self.totalpath, cv2.IMREAD_GRAYSCALE)
img = self._remove_line_(img)
result = self._split_word_(img)
# ??????????????????
if len(result) == 0:
print '???????...'
while len(result) == 0:
if self._generate_image_():
img, result = self._deal_image_()
print '?????????'
return img, result
def _get_data_(num, pic_dict=path):
# ???????
imgdata = []
labeldata = []
# ?????
checkcount = 50
nowcount = 0
# ???????????
class Getoutofloop(Exception):
pass
try:
while True:
for root, dirs, files in os.walk(pic_dict):
for dir in dirs:
for img in os.walk(os.path.join(root, dir)):
for imagename in img[2]:
if random.randint(0, 80) < 2:
image = cv2.imread(str(img[0]) + '/' + str(imagename), cv2.IMREAD_GRAYSCALE)
image = image.astype(np.float32)
image = np.multiply(image, 1.0 / 255.0)
imgdata.append(np.ravel(image))
tmplabel = img[0]
tmplabel = tmplabel[len(tmplabel) - 1]
labeldata.append(tmplabel)
nowcount += 1
if nowcount == checkcount:
raise Getoutofloop()
else:
continue
except Getoutofloop:
pass
imgdata = np.array(imgdata)
labeldata = dc._one_hot_(np.array(labeldata))
return imgdata, labeldata
# TensorFlow????
def prepare_expected_mask(mask_path):
im = cv2.resize(cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE), (output_mask_size, output_mask_size)).astype(np.float32)
# replace visible color with 1 (actual mask)
im[im > 0] = 1
# 0 -> -1
im[im == 0] = -1
return im
def __iter__(self):
#print('iter')
init_state_names = [x[0] for x in self.init_states]
for k in range(self.count):
data = []
label = []
for i in range(self.batch_size):
img_name = self.image_set_index[i + k*self.batch_size]
img = cv2.imread(os.path.join(self.data_path, img_name + '.jpg'), cv2.IMREAD_GRAYSCALE)
#img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img = cv2.resize(img, self.data_shape)
img = img.reshape((1, data_shape[1], data_shape[0]))
#print(img)
#img = img.transpose(1, 0)
#img = img.reshape((data_shape[0] * data_shape[1]))
img = np.multiply(img, 1/255.0)
#print(img)
data.append(img)
ret = np.zeros(self.num_label, int)
plate_str = self.gt[int(img_name)]
#print(plate_str)
for number in range(len(plate_str)):
ret[number] = self.classes.index(plate_str[number]) + 1
#print(ret)
label.append(ret)
data_all = [mx.nd.array(data)] + self.init_state_arrays
label_all = [mx.nd.array(label)]
data_names = ['data'] + init_state_names
label_names = ['label']
data_batch = SimpleBatch(data_names, data_all, label_names, label_all)
yield data_batch