def checkImageIsValid(imageBin):
if imageBin is None:
return False
try:
imageBuf = np.fromstring(imageBin, dtype=np.uint8)
img = cv2.imdecode(imageBuf, cv2.IMREAD_GRAYSCALE)
imgH, imgW = img.shape[0], img.shape[1]
except:
return False
else:
if imgH * imgW == 0:
return False
return True
python类imdecode()的实例源码
def decode(self, byte_list):
return cv2.imdecode(byte_list, cv2.IMREAD_COLOR)
def decode(self, data):
msg = image_t.decode(data)
if msg.pixelformat == image_t.PIXEL_FORMAT_GRAY:
return im_resize(np.asarray(bytearray(msg.data), dtype=np.uint8).reshape(msg.height, msg.width), scale=self.scale)
elif msg.pixelformat == image_t.PIXEL_FORMAT_MJPEG:
im = cv2.imdecode(np.asarray(bytearray(msg.data), dtype=np.uint8), -1)
return im_resize(im, scale=self.scale)
else:
raise RuntimeError('Unknown pixelformat for ImageDecoder')
def decode_rgb(self, data):
w, h = data.image.width, data.image.height;
if data.image.image_data_format == self.image_msg_t_.VIDEO_RGB_JPEG:
img = cv2.imdecode(np.asarray(bytearray(data.image.image_data), dtype=np.uint8), -1)
bgr = img.reshape((h,w,3))[::self.skip, ::self.skip, :]
else:
img = np.fromstring(data.image.image_data, dtype=np.uint8)
rgb = img.reshape((h,w,3))[::self.skip, ::self.skip, :]
bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
if not self.bgr:
return cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
else:
return bgr
def compressed_imgmsg_to_cv2(cmprs_img_msg, desired_encoding = "passthrough"):
"""
Convert a sensor_msgs::CompressedImage message to an OpenCV :cpp:type:`cv::Mat`.
:param cmprs_img_msg: A :cpp:type:`sensor_msgs::CompressedImage` message
:param desired_encoding: The encoding of the image data, one of the following strings:
* ``"passthrough"``
* one of the standard strings in sensor_msgs/image_encodings.h
:rtype: :cpp:type:`cv::Mat`
:raises CvBridgeError: when conversion is not possible.
If desired_encoding is ``"passthrough"``, then the returned image has the same format as img_msg.
Otherwise desired_encoding must be one of the standard image encodings
This function returns an OpenCV :cpp:type:`cv::Mat` message on success, or raises :exc:`cv_bridge.CvBridgeError` on failure.
If the image only has one channel, the shape has size 2 (width and height)
"""
str_msg = cmprs_img_msg.data
buf = np.ndarray(shape=(1, len(str_msg)),
dtype=np.uint8, buffer=cmprs_img_msg.data)
im = cv2.imdecode(buf, cv2.IMREAD_ANYCOLOR)
if desired_encoding == "passthrough":
return im
try:
res = cvtColor2(im, "bgr8", desired_encoding)
except RuntimeError as e:
raise CvBridgeError(e)
return res
def read_image(conn):
try:
length = int(recvall(conn, 16))
except:
import sys
print "Unexpected error:", sys.exc_info()[0]
return False, None
stringData = recvall(conn, length)
data = np.fromstring(stringData, dtype='uint8')
decimg = cv2.imdecode(data, 1)
print 'Image received ', decimg.shape
return True, decimg
def predict_knn(image_file):
image = cv2.imdecode(np.fromstring(image_file.read(), np.uint8), cv2.CV_LOAD_IMAGE_UNCHANGED)
if image is not None:
features = np.array([extract_color_histogram(image)])
loaded_model = pickle.load(open(MODEL_PATH + "/knn_model.sav", 'rb'))
return loaded_model.predict(features)[0]
else:
raise "Failed"
def predict_mlp(image_file):
image = cv2.imdecode(np.fromstring(image_file.read(), np.uint8), cv2.CV_LOAD_IMAGE_UNCHANGED)
if image is not None:
features = np.array([image_to_feature_vector(image)])
loaded_model = pickle.load(open(MODEL_PATH + "/mlp_model.sav", 'rb'))
scaler = pickle.load(open(MODEL_PATH + "/scaler_model.sav", "rb"))
features = scaler.transform(features)
return loaded_model.predict(features)[0]
else:
raise "Failed"
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 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 cv_test(original_image_name):
with open(original_image_name) as f:
img = cv2.imdecode(f, 1)
img2 = cv2.imread(original_image_name)
if img == img2:
print("yes you are right")
else:
print("can not do this")
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 format_image(image):
if len(image.shape) > 2 and image.shape[2] == 3:
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
else:
image = cv2.imdecode(image, cv2.CV_LOAD_IMAGE_GRAYSCALE)
faces = cascade_classifier.detectMultiScale(
image,
scaleFactor = 1.3,
minNeighbors = 5
)
# None is we don't found an image
if not len(faces) > 0:
return None
max_area_face = faces[0]
for face in faces:
if face[2] * face[3] > max_area_face[2] * max_area_face[3]:
max_area_face = face
# Chop image to face
face = max_area_face
image = image[face[1]:(face[1] + face[2]), face[0]:(face[0] + face[3])]
# Resize image to network size
try:
image = cv2.resize(image, (SIZE_FACE, SIZE_FACE), interpolation = cv2.INTER_CUBIC) / 255.
except Exception:
print("[+] Problem during resize")
return None
# cv2.imshow("Lol", image)
# cv2.waitKey(0)
return image
# Load Model
def rcv():
data = b''
while 1:
try:
r = client_socket.recv(90456)
if len(r) == 0:
exit(0)
a = r.find(b'END!')
if a != -1:
data += r[:a]
break
data += r
except Exception as e:
print(e)
continue
nparr = numpy.fromstring(data, numpy.uint8)
frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
if type(frame) is type(None):
pass
else:
try:
cv2.imshow(name,frame)
if cv2.waitKey(10) == ord('q'):
client_socket.close()
sys.exit()
except:
client_socket.close()
exit(0)
def _open_data_url(data, flag=cv2.IMREAD_COLOR):
pos = data.find('base64,')
if pos == -1:
raise IOError("data url is invalid, head %s" % data[:20])
pos += len('base64,')
raw_data = base64.decodestring(data[pos:])
image = np.asarray(bytearray(raw_data), dtype="uint8")
image = cv2.imdecode(image, flag)
return image
def url_to_image(url, flag=cv2.IMREAD_COLOR):
""" download the image, convert it to a NumPy array, and then read
it into OpenCV format """
resp = urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, flag)
return image
def str2img(jpgstr, orientation=None):
import numpy as np
import cv2
arr = np.fromstring(jpgstr, np.uint8)
img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
if orientation == 1:
return cv2.flip(cv2.transpose(img), 0) # counter-clockwise
if orientation == 3:
return cv2.flip(cv2.transpose(img), 1) # clockwise
return img
def download_image(url):
response = requests.get(url, stream=True, timeout=5)
# TODO use grequests
# Raise exception on error
response.raise_for_status()
numpy_array = np.asarray(bytearray(response.raw.read()), dtype=np.uint8)
image = cv2.imdecode(numpy_array, cv2.IMREAD_COLOR)
# TODO: handle transparency (load using cv2.IMREAD_UNCHANGED and convert alpha layer to white?)
return image
def get_img_from_screen_shot(self):
screen_shot = self.take_png_screenshot()
nparr = np.fromstring(screen_shot, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
return img
def get_mjpeg_stream_image(stream):
global bytes
while True:
bytes += stream.read(20000)
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:]
img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
q.put_nowait(img)
cv2.waitKey(1)