Saving GeoTiff with color scheme - arrays

I am trying to save a numpy array output as a GeoTiff, and have the code running mostly successfully, but the output image has a sepia-toned scale for the data (instead of a normal color scheme like my code produces for the image), and a black background (instead of the white/no-data background that my code produces for the image).
Here's the code for saving my array to a GeoTiff. Can I add a line in somewhere about making no-data = 0, and making the data scheme be colored?
from osgeo import gdal, osr, ogr, os
from gdalconst import *
def array2raster(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,array):
cols = array.shape[1]
rows = array.shape[0]
originX = rasterOrigin[0]
originY = rasterOrigin[1]
driver = gdal.GetDriverByName( 'GTiff' )
outRaster = driver.Create(newRasterfn, cols, rows, 1, gdal.GDT_Float32)
outRaster.SetGeoTransform((originX, pixelWidth, 0, originY, 0, pixelHeight))
outband = outRaster.GetRasterBand(1)
outband.WriteArray(array)
# outRaster = driver.Create( 'CORDC_GTIFF/working_CA.tiff', 300, 300, 1, gdal.GDT_Int32)
proj = osr.SpatialReference()
proj.ImportFromEPSG(4326)
outRaster.SetProjection(proj.ExportToWkt())
# geotransform = (1,0.1,0,40,0,0.1)
rasterOrigin = (-127,42)
pixelWidth = .01
pixelHeight = .01
newRasterfn = 'CORDC_GTIFF/cordc_working_CA.tif'
array = np.array(spd)
reversed_arr = array[::-1] # reverse array so the tif looks like the array
array2raster(newRasterfn,rasterOrigin,pixelWidth,pixelHeight,reversed_arr) # convert array to raster

You can set the no data value using the band's SetNoDataValue method:
outband = outRaster.GetRasterBand(1)
outband.SetNoDataValue(0)
outband.WriteArray(array)
Areas matching the no data value should then be displayed as transparent

Related

getattribute in OSL is not giving expected results

I'm working on a custom OSL shader for Maya. I'm adding attributes to the shape node of objects and using getattribute() in my OSL code to manipulate those attributes. I have attributes for color correct, base color, rim width and rim color. (the last 2 are for facing ratio). My OSL always compiles and I'm always able to connect it to the material I'm using. But every time I check if it's working in the Arnold render view, my sliders on my attributes don't do anything. The goal is to have an image file connected to the base color of the material and have the color correct node affect base color (which would affect the texture file)
At first I thought my problem was I was trying to do too much in a single OSL node (I was using getattribute for all of the attributes I listed above). So I tried isolating it to just the color correct attribute and still nothing. Is anyone familiar with OSL and can help me?
This is what my OSL code is for color correct:
shader
colorCorrect
(
float modifier = 1[[float min = 0, float max = 72]],
color bob = 0,
output color result = 0
)
{
color temp = transformc("rgb", "hsv", bob);
temp[0] = temp[0] * modifier;
result = transformc("hsv", "rgb", temp);
}
This is what my OSL code is for facing ratio:
shader
Velvet(
float rim_width = 0.2
[[
string label = "Rim Width",
]],
color basecolor = color(1,1,1)
[[
string label = "Base Color",
string widget = "checkBox",
]],
color rimcolor = color(1,0,0)
[[
string label = "Rim Color",
]],
output color resultRGB = 0,
output float resultF = 0)
{
vector i = normalize(I);
vector n = normalize(N);
float d = fabs(dot(-i, n));
d = smoothstep(rim_width, 1.0, d);
getattribute("base_color", resultRGB = mix(rimcolor, basecolor, d));
getattribute("rim_width", resultF = d - 0.5);
}

Error message "AttributeError: 'DatasetReader' object has no attribute 'open'" when trying to convert numpy array to GeoTiff

I was wondering if someone could help me with an error message I am getting. First allow me to brief my workflow
imported raster image via rasterio.open
converted raster to array via raster.read(band number)
did some calculations on the array
trying to convert the final results into geotiff
But when I am trying to execute my codes I am getting the followin error message:
**AttributeError: 'DatasetReader' object has no attribute 'open'
here are my codes
# Get necessary information
driver = "GTiff"
nlines = raster.height
ncols = raster.width
nbands = raster.count
data_type = "float32"
crs = raster.crs
transform = raster.transform
count = raster.count
file_name = "C:/file_path/file_name.tif"
#Writing the GeoTiff
with raster.open("C:/file_path/file_name.tif", "w",
driver = driver,
height = height,
width = width,
count = count,
dtype = dtype,
crs = crs,
transform = transform) as dst:
dst.write(raster_array)
Trying to write numpy array as GeoTiff
Even checked is my data is a numpy array, and the answer was TRUE

I want to recognize an image with TensorFlow. I'm getting a shape error, but what do I do?

GmdMiss_Folder = os.path.join(os.getcwd(), '..', 'Photo', 'GMD Miss')
GmdMiss_List = os.listdir(GmdMiss_Folder)
for i in range(0, len(GmdMiss_List)):
Img = os.path.join(os.getcwd(), GmdMiss_Folder, GmdMiss_List[i])
Img = cv2.imread(Img, cv2.IMREAD_GRAYSCALE)
Img = np.array(Img)
Img = cv2.resize(Img, dsize=(1920, 1080), interpolation=cv2.INTER_AREA)
Img_Miss_List.append(Img)
i=0
while True:
Img = Img_Miss_List[i]
with tf.Session() as sess:
graph = tf.Graph()
with graph.as_default():
with tf.name_scope("Convolution"):
Img = Convolution(Img)
i += 1
...
The codes below are omitted
...
def Convolution(img):
kernel = tf.Variable(tf.truncated_normal(shape=[180, 180, 3, 3], stddev=0.1))
img = img.astype('float32')
img = tf.nn.conv2d(np.expand_dims(img, 0), kernel, strides=[ 1, 15, 15, 1], padding='VALID')
return img
error is ..
ValueError: Shape must be rank 4 but is rank 3 for
'Convolution/Conv2D' (op: 'Conv2D') with input shapes: [1,1080,1920],
[180,180,3,3].
Your conv2D kernel [filter_height, filter_width, in_channels, out_channels] expects that the input image has 3 channels and it's a 4D tensor with shape [batch, in_height, in_width, in_channels] whereas you have load the input image in grayscale format. Therefore you need to load the color image having 3 channels:
Img = cv2.imread(Img) # By default cv2 load image in BGR format
Img = cv2.cvtColor(Img, cv2.COLOR_BGR2RGB) # convert BGR to RGB format
Hope it will help.

Getting black and white image when doing rotation?

I want to rotate my image by 45 degree. I have defined a function for the same. When I run it over my RGB images, it is getting saved as grayscale images?
def rotateImage(image, angle):
row,col = image.shape
center=tuple(np.array([row,col])/2)
rot_mat = cv2.getRotationMatrix2D(center,angle,1.0)
new_image = cv2.warpAffine(image, rot_mat, (col,row))
return new_image
rotate_img_path = '../data/rotate_45_img'
rotate_mask_path = '../data/rotate_45_mask'
real_img_path = '../data/img'
real_mask_path = '../data/mask'
for img in os.listdir(real_img_path):
edge_img = cv2.imread(os.path.join(real_img_path,img))
edges = rotateImage(edge_img, 45)
cv2.imwrite(os.path.join(rotate_img_path, img), edges)
print("Finished Copying images")
for img in os.listdir(real_mask_path):
edge_img = cv2.imread(os.path.join(real_mask_path,img))
edges = rotateImage(edge_img, 45)
cv2.imwrite(os.path.join(rotate_mask_path, img), edges)
# cv2.imwrite('edge_' + '.jpg', edges)
print("Finished Copying masks")
A clue here may be
row,col = image.shape
which would raise an error if image was three dimensional (i.e., in color with separate channels for B, G, and R) instead of two (i.e., grayscale). Unless you're reading RGB images with code not shown here, this suggests that your images are already grayscale.

How do I declare and call a function and array in Visual FoxPro 9.0

I'm trying to write a basic function that takes the values of 5 textboxes. I want to double the value of the first 2 Boxes to replace their former values with them and save the other 3 inside of an array. Then I want a for-loop to take the values inside of the array and get their sum in a new variable, which I want to display in a seperate TextBox.
Sorry for asking such an odd question but at the job I've just started it's tradition for apprentices to solves a bunch of these problems in FoxPro.
You could paste the following code into a new PRG, e.g. by typing Modify Command into the Command Window, and then paste it there.
LOCAL oForm as Form
oForm = CREATEOBJECT("TestForm")
oForm.Show(1)
RETURN
DEFINE CLASS TestForm as Form
AutoCenter = .T.
ADD OBJECT TextBox1 as TextBox WITH Left = 20, Top = 20, Value = 1
ADD OBJECT TextBox2 as TextBox WITH Left = 20, Top = 50, Value = 2
ADD OBJECT TextBox3 as TextBox WITH Left = 20, Top = 80, Value = 3
ADD OBJECT TextBox4 as TextBox WITH Left = 20, Top = 110, Value = 4
ADD OBJECT TextBox5 as TextBox WITH Left = 20, Top = 140, Value = 5
ADD OBJECT theOtherTextBox as TextBox WITH Left = 200, Top = 20
ADD OBJECT cmdTest as CommandButton WITH Left = 200, Top = 80
PROCEDURE cmdTest.Click
Thisform.TextBox1.Value = Thisform.TextBox1.Value * 2
Thisform.TextBox2.Value = Thisform.TextBox2.Value * 2
LOCAL ARRAY laTest[3]
STORE Thisform.TextBox3.Value TO laTest[1]
STORE Thisform.TextBox4.Value TO laTest[2]
STORE Thisform.TextBox5.Value TO laTest[3]
LOCAL lnSum, lnValue
lnSum = 0
FOR lnValue = 1 TO ALEN(laTest)
lnSum = m.lnSum + laTest[m.lnValue]
ENDFOR && or alternatively
lnSum = 0
FOR EACH lnValue IN laTest
lnSum = m.lnSum + m.lnValue
ENDFOR
Thisform.theOtherTextBox.Value = m.lnSum
ENDPROC
ENDDEFINE
FWIW, the code-as-text presentation is just for the browser demo - in a real VFP project, you'd probably rather design "visual" things in the visual Form or Class designers, good luck John Doe

Resources