I am trying to save an image in Python using Opencv's imwrite. The image name is randomized using tempfile library. But the image is not getting saved as it throws the error
"[ WARN:[email protected]] global D:\a\opencv-python\opencv-python\opencv\modules\imgcodecs\src\loadsave.cpp (773) cv::imwrite_ imwrite_('C:\Users\Max\AppData\Local\Temp\Compare_2ia3ttp7.png'): can't open file for writing: permission denied".
def contourConversion(imgToNegative, B, G, R):
gray = cv2.cvtColor(imgToNegative, cv2.COLOR_BGR2GRAY)
edged = cv2.Canny(gray, 30, 200)
#cv2.waitKey(0)
# Finding Contours
# Use a copy of the image e.g. edged.copy()
# since findContours alters the image
contours, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
counOut_img = cv2.drawContours(imgToNegative, contours, -1, (B, G, R), 2)
return counOut_img
#Master Image is in Red Countours
#Testing Image is in Purple Countours
MasterConverted = contourConversion(perfect_img, 0, 0, 255)
TestingConverted = contourConversion(test_img, 255, 0, 255)
Out_img_final = cv2.addWeighted(MasterConverted, 0.4,TestingConverted, 0.4, 0)
tf = tempfile.NamedTemporaryFile(suffix=".png",prefix="Compare_")
#var_name = tf.name
#path = "C:\\Users\\Max\\OneDrive\\Desktop\\CanspiritInternship\\autocamera"
cv2.imwrite(tf.name, Out_img_final)
#cv2.imwrite(os.path.join(path , tf.name),Out_img_final)
cv2.waitKey(0)
#cv2.imwrite("ContourComparison.png",Out_img_final)
CodePudding user response:
NamedTemporaryFile
opened the file already and keeps a handle on it:
tf = tempfile.NamedTemporaryFile(suffix=".png",prefix="Compare_")
You can't (ordinarily) open the same file for writing twice.
You are trying to open it again (with imwrite
), which is supposed to fail because the file is still open from the NamedTemporaryFile
call.
%LOCALAPPDATA%
(Appdata\Local
) is user-writable. Appdata\Local\Temp
specifically is writable by the user. That is its whole purpose.
%APPDATA%
(Appdata\Roaming
) appears to be writable as well (tested on Win10). The system does not prevent apps from messing with each other, or you with that data.
CodePudding user response:
You need admin access in Windows to do anything in AppData. Best thing to do would be to just write the image somewhere else.
Above solution would be preferable, but otherwise you may be able to run Python as administrator - not sure if that will work, but give it a go.