def __rand__(self, other):
return bitwise_and(other, self)
python类bitwise_and()的实例源码
def main():
"""Main demo."""
# Load survey data
llh, data = get_flightlines()
decimate = 5
llh = llh[::decimate]
data = data[::decimate]
# Select by height intervals (57% of the data)
hrange = [95., 105.]
keep = np.bitwise_and(llh[:, 2] > hrange[0], llh[:,2] < hrange[1])
llh = llh[keep]
data = data[keep]
# Write out the reduced llh, data
sf = shapefile.Writer(shapefile.POINT)
outname = data_root + 'new_flightlines'
log.info('Writing shapefile')
sf.field("K")
sf.field("Th")
sf.field("U")
for ll, dat in tqdm(zip(llh, data)):
sf.point(ll[0], ll[1], ll[2])
sf.record(K=dat[0], Th=dat[1], U=dat[2])
sf.save(outname)
log.info('Done!')
def create_binary_wf_data(wf, sync_mkr=0, samp_mkr=0, vertical_resolution=12):
"""Given numpy arrays of waveform and marker data convert to binary format.
Assumes waveform data is np.float in range -1 to 1 and marker data can be cast to bool
Binary format is waveform in MSB and and markers in LSB
waveform sync_mkr samp_mkr
15 downto 4/2 1 0
"""
#cast the waveform to integers
if not((vertical_resolution == 12) or (vertical_resolution == 14)):
raise ValueError("vertical resolution must be 12 or 14 bits")
#convert waveform to integers
scale_factor = 2**(vertical_resolution-1)
bin_data = np.int16((scale_factor-1)*np.array(wf))
#clip if necessary
if np.max(bin_data) > scale_factor-1 or np.min(bin_data) < -scale_factor:
warnings.warn("Clipping waveform. Max value: {:d} Min value: {:d}. Scale factor: {:d}.".format(np.max(bin_data), np.min(bin_data),scale_factor))
bin_data = np.clip(bin_data, -scale_factor, scale_factor-1)
# bin_data = bin_data.byteswap()
#shift up to the MSB
bin_data = np.left_shift(bin_data, 4 if vertical_resolution == 12 else 2)
#add in the marker bits
bin_data = np.bitwise_or(bin_data, np.bitwise_or(np.left_shift(np.bitwise_and(sync_mkr, 0x1), 1), np.bitwise_and(samp_mkr, 0x1)))
return bin_data
def get_mask_overlap(mask1, mask2):
intersect = np.bitwise_and(mask1, mask2).sum()
union = np.bitwise_or(mask1, mask2).sum()
return 1.0 * intersect / union
def training_stress_pma_grappe_score(X, pma):
"""Compute the training stress score using the MAP.
Parameters
----------
X : array-like, shape (n_samples, )
Array containing the power intensities for a ride.
pma : float
Maximum Anaerobic Power.
Returns
-------
tss_score: float
Return the training stress score.
"""
# Check the consistency of X and pma
if len(X.shape) != 1:
raise ValueError('X should have 1 dimension. Got {}, instead'.format(
len(X.shape)))
# Compute the stress for each item of the ESIE
tss_grappe = 0.
for key_sc in TS_SCALE_GRAPPE.keys():
# Count the number of elements which corresponds to as sec
# We need to convert it to minutes
curr_stress = np.count_nonzero(
np.bitwise_and(X >= ESIE_SCALE_GRAPPE[key_sc][0] * pma,
X < ESIE_SCALE_GRAPPE[key_sc][1] * pma)) / 60
# Compute the cumulative stress
tss_grappe += curr_stress * TS_SCALE_GRAPPE[key_sc]
return tss_grappe
def getCrop(self, dpt, xstart, xend, ystart, yend, zstart, zend, thresh_z=True):
"""
Crop patch from image
:param dpt: depth image to crop from
:param xstart: start x
:param xend: end x
:param ystart: start y
:param yend: end y
:param zstart: start z
:param zend: end z
:param thresh_z: threshold z values
:return: cropped image
"""
if len(dpt.shape) == 2:
cropped = dpt[max(ystart, 0):min(yend, dpt.shape[0]), max(xstart, 0):min(xend, dpt.shape[1])].copy()
# add pixels that are out of the image in order to keep aspect ratio
cropped = numpy.pad(cropped, ((abs(ystart)-max(ystart, 0),
abs(yend)-min(yend, dpt.shape[0])),
(abs(xstart)-max(xstart, 0),
abs(xend)-min(xend, dpt.shape[1]))), mode='constant', constant_values=0)
elif len(dpt.shape) == 3:
cropped = dpt[max(ystart, 0):min(yend, dpt.shape[0]), max(xstart, 0):min(xend, dpt.shape[1]), :].copy()
# add pixels that are out of the image in order to keep aspect ratio
cropped = numpy.pad(cropped, ((abs(ystart)-max(ystart, 0),
abs(yend)-min(yend, dpt.shape[0])),
(abs(xstart)-max(xstart, 0),
abs(xend)-min(xend, dpt.shape[1])),
(0, 0)), mode='constant', constant_values=0)
else:
raise NotImplementedError()
if thresh_z is True:
msk1 = numpy.bitwise_and(cropped < zstart, cropped != 0)
msk2 = numpy.bitwise_and(cropped > zend, cropped != 0)
cropped[msk1] = zstart
cropped[msk2] = 0. # backface is at 0, it is set later
return cropped
def delta_plus(self, nodes):
'''
Returns the list of edges forwarding from a set of nodes
'''
bool_indices_head = np.array([x[0] in nodes for x in self.edges])
bool_indices_tail = np.array([x[1] not in nodes for x in self.edges])
bool_indices_edges = np.bitwise_and(
bool_indices_head, bool_indices_tail)
return self.edges[bool_indices_edges]
def delta_minus(self, nodes):
'''
Returns the list of edges backwarding from a set of nodes
'''
bool_indices_head = np.array([x[0] not in nodes for x in self.edges])
bool_indices_tail = np.array([x[1] in nodes for x in self.edges])
bool_indices_edges = np.bitwise_and(
bool_indices_head, bool_indices_tail)
return self.edges[bool_indices_edges]
def delta_plus(self, nodes):
'''
Returns the list of edges forwarding from a set of nodes
'''
bool_indices_head = np.array([x[0] in nodes for x in self.edges])
bool_indices_tail = np.array([x[1] not in nodes for x in self.edges])
bool_indices_edges = np.bitwise_and(
bool_indices_head, bool_indices_tail)
return self.edges[bool_indices_edges]
def delta_minus(self, nodes):
'''
Returns the list of edges backwarding from a set of nodes
'''
bool_indices_head = np.array([x[0] not in nodes for x in self.edges])
bool_indices_tail = np.array([x[1] in nodes for x in self.edges])
bool_indices_edges = np.bitwise_and(
bool_indices_head, bool_indices_tail)
return self.edges[bool_indices_edges]
def binary_and(a,b):
"""Compare two binary arrays of the same length and return a third one,
the bitwise addition of the first two."""
# return np.logical_and(a,b) # does not work with packed arrays
return np.bitwise_and(a, b)
def test_truth_table_bitwise(self):
arg1 = [False, False, True, True]
arg2 = [False, True, False, True]
out = [False, True, True, True]
assert_equal(np.bitwise_or(arg1, arg2), out)
out = [False, False, False, True]
assert_equal(np.bitwise_and(arg1, arg2), out)
out = [False, True, True, False]
assert_equal(np.bitwise_xor(arg1, arg2), out)
def __iand__(self, other):
np.bitwise_and(self, other, out=self)
return self
def _bin_results(self, length, results):
"""
Add hits to the bins corresponding to these results. length_hit_bins
is flattened, so we need to figure out the offset for this hit by
factoring the sizes of the other dimensions.
"""
hit_bin = np.zeros(results.shape[0], dtype='int64')
multi = 1
good = np.ones(results.shape[0], dtype='bool')
for dim in range(len(self.out_labels)):
for d1 in range(dim):
multi *= self.bin_edges[d1].size
if dim == 0 and len(self.out_labels)==1:
try:
digi = np.digitize(results, self.bin_edges[dim])
except ValueError:
# The user probably did something like
# return a * b rather than
# return a[0] * b[0], which will only happen
# for single field functions.
digi = np.digitize(results[0], self.bin_edges[dim])
else:
digi = np.digitize(results[:,dim], self.bin_edges[dim])
too_low = (digi == 0)
too_high = (digi == self.bin_edges[dim].size)
self.too_low[dim] += (too_low).sum()
self.too_high[dim] += (too_high).sum()
newgood = np.bitwise_and(np.invert(too_low), np.invert(too_high))
good = np.bitwise_and(good, newgood)
hit_bin += np.multiply((digi - 1), multi)
digi_bins = np.arange(self.length_bin_hits[length].size+1)
hist, digi_bins = np.histogram(hit_bin[good], digi_bins)
self.length_bin_hits[length] += hist
def spread_bitsv(ival, level):
res = np.zeros_like(ival, dtype='int64')
for i in range(level):
ares = np.bitwise_and(ival, 1<<i) << (i*2)
np.bitwise_or(res, ares, res)
return res
def extract_bv(image):
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
contrast_enhanced_green_fundus = clahe.apply(image)
# applying alternate sequential filtering (3 times closing opening)
r1 = cv2.morphologyEx(contrast_enhanced_green_fundus, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1)
R1 = cv2.morphologyEx(r1, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1)
r2 = cv2.morphologyEx(R1, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)), iterations = 1)
R2 = cv2.morphologyEx(r2, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)), iterations = 1)
r3 = cv2.morphologyEx(R2, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(23,23)), iterations = 1)
R3 = cv2.morphologyEx(r3, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(23,23)), iterations = 1)
f4 = cv2.subtract(R3,contrast_enhanced_green_fundus)
f5 = clahe.apply(f4)
# removing very small contours through area parameter noise removal
ret,f6 = cv2.threshold(f5,15,255,cv2.THRESH_BINARY)
mask = np.ones(f5.shape[:2], dtype="uint8") * 255
im2, contours, hierarchy = cv2.findContours(f6.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt) <= 200:
cv2.drawContours(mask, [cnt], -1, 0, -1)
im = cv2.bitwise_and(f5, f5, mask=mask)
ret,fin = cv2.threshold(im,15,255,cv2.THRESH_BINARY_INV)
newfin = cv2.erode(fin, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)
# removing blobs of microaneurysm & unwanted bigger chunks taking in consideration they are not straight lines like blood
# vessels and also in an interval of area
fundus_eroded = cv2.bitwise_not(newfin)
xmask = np.ones(image.shape[:2], dtype="uint8") * 255
x1, xcontours, xhierarchy = cv2.findContours(fundus_eroded.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in xcontours:
shape = "unidentified"
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.04 * peri, False)
if len(approx) > 4 and cv2.contourArea(cnt) <= 3000 and cv2.contourArea(cnt) >= 100:
shape = "circle"
else:
shape = "veins"
if(shape=="circle"):
cv2.drawContours(xmask, [cnt], -1, 0, -1)
finimage = cv2.bitwise_and(fundus_eroded,fundus_eroded,mask=xmask)
blood_vessels = cv2.bitwise_not(finimage)
dilated = cv2.erode(blood_vessels, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7)), iterations=1)
#dilated1 = cv2.dilate(blood_vessels, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)
blood_vessels_1 = cv2.bitwise_not(dilated)
return blood_vessels_1
def extract_bv(image):
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
contrast_enhanced_green_fundus = clahe.apply(image)
# applying alternate sequential filtering (3 times closing opening)
r1 = cv2.morphologyEx(contrast_enhanced_green_fundus, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1)
R1 = cv2.morphologyEx(r1, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)), iterations = 1)
r2 = cv2.morphologyEx(R1, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)), iterations = 1)
R2 = cv2.morphologyEx(r2, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(11,11)), iterations = 1)
r3 = cv2.morphologyEx(R2, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(23,23)), iterations = 1)
R3 = cv2.morphologyEx(r3, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(23,23)), iterations = 1)
f4 = cv2.subtract(R3,contrast_enhanced_green_fundus)
f5 = clahe.apply(f4)
# removing very small contours through area parameter noise removal
ret,f6 = cv2.threshold(f5,15,255,cv2.THRESH_BINARY)
mask = np.ones(f5.shape[:2], dtype="uint8") * 255
im2, contours, hierarchy = cv2.findContours(f6.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt) <= 200:
cv2.drawContours(mask, [cnt], -1, 0, -1)
im = cv2.bitwise_and(f5, f5, mask=mask)
ret,fin = cv2.threshold(im,15,255,cv2.THRESH_BINARY_INV)
newfin = cv2.erode(fin, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)
# removing blobs of microaneurysm & unwanted bigger chunks taking in consideration they are not straight lines like blood
# vessels and also in an interval of area
fundus_eroded = cv2.bitwise_not(newfin)
xmask = np.ones(image.shape[:2], dtype="uint8") * 255
x1, xcontours, xhierarchy = cv2.findContours(fundus_eroded.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in xcontours:
shape = "unidentified"
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.04 * peri, False)
if len(approx) > 4 and cv2.contourArea(cnt) <= 3000 and cv2.contourArea(cnt) >= 100:
shape = "circle"
else:
shape = "veins"
if(shape=="circle"):
cv2.drawContours(xmask, [cnt], -1, 0, -1)
finimage = cv2.bitwise_and(fundus_eroded,fundus_eroded,mask=xmask)
blood_vessels = cv2.bitwise_not(finimage)
dilated = cv2.erode(blood_vessels, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7)), iterations=1)
#dilated1 = cv2.dilate(blood_vessels, cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3)), iterations=1)
blood_vessels_1 = cv2.bitwise_not(dilated)
return blood_vessels_1
def mask_real_image(color, depth, depth_render):
mask = (depth_render != 0).astype(np.uint8)[:, :, np.newaxis]
masked_rgb = color * mask
masked_hsv = cv2.cvtColor(masked_rgb, cv2.COLOR_BGR2HSV)
saturation_mask = (masked_hsv[:, :, 2] <= SATURATION_THRESHOLD)[:, :, np.newaxis].astype(np.uint8)
total_mask = np.bitwise_and(mask, saturation_mask)
masked_color = color * total_mask
masked_depth = depth[:total_mask.shape[0], :total_mask.shape[1]] * total_mask[:, :, 0]
return masked_color, masked_depth
def show_occlusion(detection, rgb, depth, camera, bb_width):
pixels = compute_2Dboundingbox(detection, camera, bb_width)
depth_crop = depth[pixels[0, 0]:pixels[1, 0], pixels[0, 1]:pixels[2, 1]].astype(np.float)
mask = np.bitwise_and(depth_crop < 880, depth_crop != 0)
mask = cv2.erode(mask.astype(np.uint8), np.ones((3, 3)))
print("Occlusion level : {}".format(np.sum(mask) / (mask.shape[0] * mask.shape[1])))
cv2.imshow("object crop mask", (mask * 255))
cv2.imshow("object crop depth", ((depth_crop / np.max(depth_crop) * 255).astype(np.uint8)))
cv2.rectangle(rgb, tuple(pixels[0][::-1]), tuple(pixels[3][::-1]), (0, 0, 255), 2)
test_umath.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def test_truth_table_bitwise(self):
arg1 = [False, False, True, True]
arg2 = [False, True, False, True]
out = [False, True, True, True]
assert_equal(np.bitwise_or(arg1, arg2), out)
out = [False, False, False, True]
assert_equal(np.bitwise_and(arg1, arg2), out)
out = [False, True, True, False]
assert_equal(np.bitwise_xor(arg1, arg2), out)