def start_stream(self):
bytes = None
print("starting stream...")
stream = urllib2.urlopen(self.address) #'http://192.168.100.102:8080/video'
bytes = b''
while True:
bytes += stream.read(1024)
a = bytes.find(b'\xff\xd8')
b = bytes.find(b'\xff\xd9')
if a != -1 and b != -1:
jpg = bytes[a:b+2]
bytes = bytes[b+2:]
self.image = cv2.cvtColor(cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB)
#cv2.imshow('i', self.image)
#cv2.waitKey(1)
python类IMREAD_COLOR的实例源码
def test_detector():
print('test detector:')
# load model
detector = Detector('SeetaFaceEngine/model/seeta_fd_frontal_v1.0.bin')
detector.set_min_face_size(30)
image_color = cv2.imread('data/chloecalmon.png', cv2.IMREAD_COLOR)
image_gray = cv2.cvtColor(image_color, cv2.COLOR_BGR2GRAY)
faces = detector.detect(image_gray)
for i, face in enumerate(faces):
print('({0},{1},{2},{3}) score={4}'.format(face.left, face.top, face.right, face.bottom, face.score))
cv2.rectangle(image_color, (face.left, face.top), (face.right, face.bottom), (0,255,0), thickness=2)
cv2.putText(image_color, str(i), (face.left, face.bottom),cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), thickness=1)
cv2.imshow('test', image_color)
cv2.waitKey(0)
detector.release()
def test_aligner():
print('test aligner:')
# load model
detector = Detector('SeetaFaceEngine/model/seeta_fd_frontal_v1.0.bin')
detector.set_min_face_size(30)
aligner = Aligner('SeetaFaceEngine/model/seeta_fa_v1.1.bin')
image_color = cv2.imread('data/chloecalmon.png', cv2.IMREAD_COLOR)
image_gray = cv2.cvtColor(image_color, cv2.COLOR_BGR2GRAY)
faces = detector.detect(image_gray)
for face in faces:
landmarks = aligner.align(image_gray, face)
for point in landmarks:
cv2.circle(image_color, point, 1, (0,255,0), 2)
cv2.imshow('test aligner', image_color)
cv2.waitKey(0)
aligner.release()
detector.release()
def load(self):
if self.imageType == InputType.image:
self.data = cv2.cvtColor(cv2.imread(self.filePath, cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB)
self.state = LoadState.loaded
if self.imageType == InputType.imageGrayscale:
self.data = cv2.cvtColor(cv2.imread(self.filePath, cv2.IMREAD_COLOR), cv2.COLOR_BGR2GRAY)
self.state = LoadState.loaded
elif self.imageType == InputType.saliencyMapMatlab:
self.data = (scipy.io.loadmat(self.filePath)['I'] * 255).astype(np.uint8)
self.state = LoadState.loaded
elif self.imageType == InputType.fixationMapMatlab:
self.data = (scipy.io.loadmat(self.filePath)['I']).nonzero()
self.state = LoadState.loaded
elif self.imageType == InputType.empty:
self.data = None
def nextBatch(self, batches, dataset='train'):
imgH = 300
imgW = 300
if dataset == 'train':
datalist = self.trainList
if dataset == 'test':
datalist = self.testList
randomIndex = random.sample(range(len(datalist)), batches)
images = []
for index in randomIndex:
fileName = './svt1/' + datalist[index][0]
img = cv2.imread(fileName, cv2.IMREAD_COLOR)
resized = cv2.resize(img, (imgW, imgH))
resized = np.multiply(resized, 1.0/255.0)
images.append(resized)
anns.append(datalist[x][1])
images = np.asarray(images)
return (images, anns)
def _grab_image(path=None, stream=None, url=None):
# if the path is not None, then load the image from disk
if path is not None:
image = cv2.imread(path)
# otherwise, the image does not reside on disk
else:
# if the URL is not None, then download the image
if url is not None:
resp = urllib.urlopen(url)
data = resp.read()
# if the stream is not None, then the image has been uploaded
elif stream is not None:
data = stream.read()
# convert the image to a NumPy array and then read it into
# OpenCV format
image = np.asarray(bytearray(data), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
# return the image
return image
def browse(database):
for item in database:
filename = os.path.split(item['url'])[-1]
path = image_root + filename
img = cv2.imread(path, cv2.IMREAD_COLOR)
crop = item['crop']
x = crop[0]
y = crop[1]
w = crop[2]
h = crop[3]
# Error handling
if img is None:
puts(colored.red('ERROR: loading image failed!'))
continue
cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 2)
cv2.imshow('Cropping', img)
key = cv2.waitKey()
if key == 1048603:
print 'exit'
break
def load_lmdb(lmdb_file, n_records=None):
import lmdb
import numpy as np
lmdb_file = expand_user(lmdb_file)
if os.path.exists(lmdb_file):
data = []
env = lmdb.open(lmdb_file, readonly=True, max_readers=512)
with env.begin() as txn:
cursor = txn.cursor()
begin_st = time.time()
print("Loading lmdb file {} into memory".format(lmdb_file))
for key, value in cursor:
_, target, _ = key.decode('ascii').split(':')
target = int(target)
img = cv2.imdecode(np.fromstring(value, np.uint8), cv2.IMREAD_COLOR)
data.append((img, target))
if n_records is not None and len(data) >= n_records:
break
env.close()
print("=> Done ({:.4f} s)".format(time.time() - begin_st))
return data
else:
print("Not found lmdb file".format(lmdb_file))
def exportSurfaceMask(overwriteSource):
terrainSplatMaskPath = bpy.data.scenes["Default_Location"].ImportTerrainSplatMaskPath
if bpy.context.scene.SurfaceMaskFormatValid:
print('\nbLT_Info: Surface map export started ', time.ctime())
from cv2 import imread as cv2imread, imwrite as cv2imwrite, IMREAD_COLOR as cv2IMREAD_COLOR
ProjFolderPath = bpy.data.scenes["Default_Location"].ProjFolderPath
locationName = bpy.context.scene.name
sourceSurfaceMask = cv2imread(bpy.data.scenes["Default_Location"].ImportTerrainSplatMaskPath, cv2IMREAD_COLOR)
locationSurfaceMask = cv2imread(r'{}ProjectData\Textures\TerrainMask_{}.png'.format(ProjFolderPath,locationName), cv2IMREAD_COLOR)
terrainObject = bpy.data.objects.get('Terrain_{}'.format(locationName))
sourceSurfaceMask[terrainObject['MergeTopLeftY']:terrainObject["MergeBottomRightY"],terrainObject["MergeTopLeftX"]:terrainObject["MergeBottomRightX"]] = locationSurfaceMask
if overwriteSource:
outputPath = terrainSplatMaskPath
else:
outputPath = '{}\\Output\\surfaceMask.png'.format(ProjFolderPath)
cv2imwrite(outputPath, sourceSurfaceMask)
print('bLT_Info: Surface map export finished ', time.ctime())
else:
print('\nbLT_Info:No surface map data exported!!! Source surface mask path not defined in Data Sources panel.')
preprocess_images.py 文件源码
项目:Kaggle-Cat-vs-Dog-Tensorflow-CNN
作者: jshin49
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def process_image(img, img_size, pixel_depth):
'''
Maintain aspect ratio of image while resizing
'''
img = cv2.imread(img, cv2.IMREAD_COLOR)
if (img.shape[0] >= img.shape[1]): # height is greater than width
resizeto = (img_size, int(
round(img_size * (float(img.shape[1]) / img.shape[0]))))
else:
resizeto = (
int(round(img_size * (float(img.shape[0]) / img.shape[1]))), img_size)
img = cv2.resize(img, (resizeto[1], resizeto[
0]), interpolation=cv2.INTER_CUBIC)
img = cv2.copyMakeBorder(
img, 0, img_size - img.shape[0], 0, img_size - img.shape[1], cv2.BORDER_CONSTANT, 0)
img = normalize_image(img, pixel_depth)
return img[:, :, ::-1] # turn into rgb format
def test_solution_close_to_original_implementation(self):
image = cv2.imread('testdata/source.png', cv2.IMREAD_COLOR) / 255.0
scribles = cv2.imread('testdata/scribbles.png', cv2.IMREAD_COLOR) / 255.0
alpha = closed_form_matting.closed_form_matting_with_scribbles(image, scribles)
foreground, background = solve_foreground_background(image, alpha)
matlab_alpha = cv2.imread('testdata/matlab_alpha.png', cv2.IMREAD_GRAYSCALE) / 255.0
matlab_foreground = cv2.imread('testdata/matlab_foreground.png', cv2.IMREAD_COLOR) / 255.0
matlab_background = cv2.imread('testdata/matlab_background.png', cv2.IMREAD_COLOR) / 255.0
sad_alpha = np.mean(np.abs(alpha - matlab_alpha))
sad_foreground = np.mean(np.abs(foreground - matlab_foreground))
sad_background = np.mean(np.abs(background - matlab_background))
self.assertLess(sad_alpha, 1e-2)
self.assertLess(sad_foreground, 1e-2)
self.assertLess(sad_background, 1e-2)
def decode(self, byte_list):
return cv2.imdecode(byte_list, cv2.IMREAD_COLOR)
def image_loop():
image_counter = 0
while True:
# path = '/Users/vmagro/Developer/frc/RealFullField/11.jpg'
# path = '/Users/vmagro/Developer/frc/Vision2016/test/img/11.jpg'
path = '/Users/vmagro/Developer/frc/RealFullField/' + str(image_counter) + '.jpg'
img = cv2.imread(path, cv2.IMREAD_COLOR)
image_counter = (image_counter + 1) % 350
handle_image(img)
time.sleep(33 / 1000) # slow down so its visible
def read_im(self,fname,scale=1):
'''
????
'''
# =============================================================================
# im = cv2.imread(fname, cv2.IMREAD_COLOR)
# =============================================================================
im = cv2.imdecode(np.fromfile(fname,dtype=np.uint8),-1)
if type(im)==type(None):
print(fname)
raise ValueError('Opencv read image {} error, got None'.format(fname))
return im
def pull_image(self, index):
'''Returns the original image object at index in PIL form
Note: not using self.__getitem__(), as any transformations passed in
could mess up this functionality.
Argument:
index (int): index of img to show
Return:
PIL img
'''
img_id = self.ids[index]
return cv2.imread(self._imgpath % img_id, cv2.IMREAD_COLOR)
def image_from_archive(archive, name):
"""
Load image PGM file from tar archive.
Used for tarfile loading and unit test.
"""
member = archive.getmember(name)
imagefiledata = numpy.fromstring(archive.extractfile(member).read(-1), numpy.uint8)
imagefiledata.resize((1, imagefiledata.size))
return cv2.imdecode(imagefiledata, cv2.IMREAD_COLOR)
def url_to_image(url):
# download the image, convert it to a NumPy array, and then read
# it into OpenCV format
resp = urllib.urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
# return the image
return image
def read_image(file_path):
img = cv2.imread(file_path, cv2.IMREAD_COLOR) # cv2.IMREAD_GRAYSCALE
if (img.shape[0] >= img.shape[1]): # height is greater than width
resizeto = (IMAGE_SIZE, int(round(IMAGE_SIZE * (float(img.shape[1]) / img.shape[0]))));
else:
resizeto = (int(round(IMAGE_SIZE * (float(img.shape[0]) / img.shape[1]))), IMAGE_SIZE);
img2 = cv2.resize(img, (resizeto[1], resizeto[0]), interpolation=cv2.INTER_CUBIC)
img3 = cv2.copyMakeBorder(img2, 0, IMAGE_SIZE - img2.shape[0], 0, IMAGE_SIZE - img2.shape[1], cv2.BORDER_CONSTANT,
0)
return img3[:, :, ::-1] # turn into rgb format
def read_im_and_landmarks(fname):
im = cv2.imread(fname, cv2.IMREAD_COLOR)
try:
s = get_landmarks(im,fname)
return im, s
except:
return im,fname
def load_image(self, img_id):
img = self.coco.loadImgs(img_id)[0]
img_str = '%simages/%s/%s' % (self.root, self.real_split, img['file_name'])
if self.split == 'test-dev2015':
img_str = img_str.replace('test-dev2015', 'test2015')
im = cv2.imread(img_str, cv2.IMREAD_COLOR)
im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)/255.0
im = im.astype(np.float32)
return im